/**
 *====================================================
 * 文件名称: FinanceApplicationActionApiImpl.java
 * 修订记录：
 * No    日期				作者(操作:具体内容)
 * 1.    2015年9月26日			chenxy(创建:创建文件)
 *====================================================
 * 类描述：(说明未实现或其它不应生成javadoc的内容)
 */
package com.yuexunit.finance.project.action.v1;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

import org.apache.commons.lang.ArrayUtils;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yuexunit.account.entity.AccountEntity;
import com.yuexunit.account.service.AccountService;
import com.yuexunit.core.BusinessException;
import com.yuexunit.core.ConfigPropertites;
import com.yuexunit.finance.bulkstock.entity.BulkstockInfoEntity;
import com.yuexunit.finance.bulkstock.entity.MaterialTemplateEntity;
import com.yuexunit.finance.bulkstock.entity.lexicon.MaterialTemplateEnum;
import com.yuexunit.finance.bulkstock.entity.lexicon.MeasurementEnum;
import com.yuexunit.finance.bulkstock.service.MaterialTemplateService;
import com.yuexunit.finance.bulkstock.service.TemporaryCreditLineService;
import com.yuexunit.finance.common.httpclient.HttpClientHelper;
import com.yuexunit.finance.common.httpclient.ServiceClientHelper;
import com.yuexunit.finance.common.util.BeanUtils;
import com.yuexunit.finance.common.util.CollectionUtils;
import com.yuexunit.finance.common.util.DateUtils;
import com.yuexunit.finance.common.util.LongUtils;
import com.yuexunit.finance.common.util.StringUtils;
import com.yuexunit.finance.context.FinanceBaseAction;
import com.yuexunit.finance.context.FinanceConstant;
import com.yuexunit.finance.context.FinanceLetterBlockingQueue;
import com.yuexunit.finance.context.FinanceSessionContext;
import com.yuexunit.finance.member.entity.CommissionScaleTableEntity;
import com.yuexunit.finance.member.entity.EnterpriseCodeEntity;
import com.yuexunit.finance.member.entity.EnterpriseEntity;
import com.yuexunit.finance.member.entity.EnterpriseGradeEntity;
import com.yuexunit.finance.member.entity.FinanceBulkstockPledgeRateEntity;
import com.yuexunit.finance.member.entity.FingerTrunkAccountMappingEntity;
import com.yuexunit.finance.member.entity.LogisticsCompanyEntity;
import com.yuexunit.finance.member.entity.SupplierCommissionGradeEntity;
import com.yuexunit.finance.member.entity.SupplierEntity;
import com.yuexunit.finance.member.entity.TemporaryCreditLineEntity;
import com.yuexunit.finance.member.entity.lexicon.AuditStateEnum;
import com.yuexunit.finance.member.service.CommissionScaleTableService;
import com.yuexunit.finance.member.service.EnterpriseCodeService;
import com.yuexunit.finance.member.service.EnterpriseGradeService;
import com.yuexunit.finance.member.service.EnterpriseService;
import com.yuexunit.finance.member.service.FinanceBulkstockPledgeRateService;
import com.yuexunit.finance.member.service.FingerTrunkAccountMappingService;
import com.yuexunit.finance.member.service.LogisticsCompanyService;
import com.yuexunit.finance.member.service.SupplierCommissionGradeService;
import com.yuexunit.finance.member.service.SupplierService;
import com.yuexunit.finance.project.FinanceCancelApplicationService;
import com.yuexunit.finance.project.action.v1.dto.BulkstockCastor;
import com.yuexunit.finance.project.action.v1.dto.FinanceApplicationCastor;
import com.yuexunit.finance.project.action.v1.dto.FinanceContractCastor;
import com.yuexunit.finance.project.action.v1.dto.FinanceLoanCastor;
import com.yuexunit.finance.project.action.v1.dto.FinanceMaterialCastor;
import com.yuexunit.finance.project.action.v1.dto.FinanceProcessCastor;
import com.yuexunit.finance.project.action.v1.model.CommissionExtractApplicationDetail;
import com.yuexunit.finance.project.action.v1.model.FiananceAuditInfo;
import com.yuexunit.finance.project.action.v1.model.FinanceAudit;
import com.yuexunit.finance.project.action.v1.model.FinanceBulkstock;
import com.yuexunit.finance.project.action.v1.model.FinanceCommissionInfoDetail;
import com.yuexunit.finance.project.action.v1.model.FinanceExpenseDetail;
import com.yuexunit.finance.project.action.v1.model.input.FinanceApplication;
import com.yuexunit.finance.project.action.v1.model.input.FinanceApplicationUpdate;
import com.yuexunit.finance.project.action.v1.model.input.FinanceProductInnerInput;
import com.yuexunit.finance.project.action.v1.model.output.ContainerInventory;
import com.yuexunit.finance.project.action.v1.model.output.FinanceApplicationDetail;
import com.yuexunit.finance.project.action.v1.model.output.FinanceAuditDetail;
import com.yuexunit.finance.project.action.v1.model.output.FinanceAuditRecordDetail;
import com.yuexunit.finance.project.action.v1.model.output.FinanceCancelApplicationDetail;
import com.yuexunit.finance.project.action.v1.model.output.FinanceCutLinesDetail;
import com.yuexunit.finance.project.action.v1.model.output.FinanceEvaluateDetail;
import com.yuexunit.finance.project.action.v1.model.output.FinanceLineInfo;
import com.yuexunit.finance.project.action.v1.model.output.FinanceProcess;
import com.yuexunit.finance.project.action.v1.model.output.FinanceWaybillDetail;
import com.yuexunit.finance.project.action.v1.model.output.HandleSuitcaseResult;
import com.yuexunit.finance.project.action.v1.model.output.ResultData;
import com.yuexunit.finance.project.action.v1.model.output.SupervisionEndallDetail;
import com.yuexunit.finance.project.action.v1.model.output.WareResultDetailData;
import com.yuexunit.finance.project.action.v1.model.output.WareResultDetailData2;
import com.yuexunit.finance.project.action.v1.model.output.WarehouseInfo;
import com.yuexunit.finance.project.action.v1.model.output.WarehouseMap;
import com.yuexunit.finance.project.entity.CommissionExtractApplicationEntity;
import com.yuexunit.finance.project.entity.ContainerBulkstockEntity;
import com.yuexunit.finance.project.entity.ContainerInventoryEntity;
import com.yuexunit.finance.project.entity.FinanceApplicationEntity;
import com.yuexunit.finance.project.entity.FinanceAuditEntity;
import com.yuexunit.finance.project.entity.FinanceAuditLogEntity;
import com.yuexunit.finance.project.entity.FinanceBulkstockColdStorageEntity;
import com.yuexunit.finance.project.entity.FinanceBulkstockDangerousEntity;
import com.yuexunit.finance.project.entity.FinanceBulkstockEntity;
import com.yuexunit.finance.project.entity.FinanceCancelApplicationEntity;
import com.yuexunit.finance.project.entity.FinanceCommissionInfoEntity;
import com.yuexunit.finance.project.entity.FinanceCompleteResultEntity;
import com.yuexunit.finance.project.entity.FinanceContainerBillEntity;
import com.yuexunit.finance.project.entity.FinanceContainerEntity;
import com.yuexunit.finance.project.entity.FinanceContainerLogEntity;
import com.yuexunit.finance.project.entity.FinanceContainerWaybillEntity;
import com.yuexunit.finance.project.entity.FinanceContractEntity;
import com.yuexunit.finance.project.entity.FinanceCutLinesEntity;
import com.yuexunit.finance.project.entity.FinanceEvaluateEntity;
import com.yuexunit.finance.project.entity.FinanceEvidentiaryCategoryEntity;
import com.yuexunit.finance.project.entity.FinanceEvidentiaryEntity;
import com.yuexunit.finance.project.entity.FinanceExpenseDetailEntity;
import com.yuexunit.finance.project.entity.FinanceFilesInfoEntity;
import com.yuexunit.finance.project.entity.FinanceLockedInfoEntity;
import com.yuexunit.finance.project.entity.FinanceMaterialEntity;
import com.yuexunit.finance.project.entity.FinanceMoneyStatementEntity;
import com.yuexunit.finance.project.entity.FinanceProcessEntity;
import com.yuexunit.finance.project.entity.FinanceProductEntity;
import com.yuexunit.finance.project.entity.FinanceProductInnerEntity;
import com.yuexunit.finance.project.entity.FinanceProductInterestItemEntity;
import com.yuexunit.finance.project.entity.FreightInfoEntity;
import com.yuexunit.finance.project.entity.InsuranceCoverageBulkstockEntity;
import com.yuexunit.finance.project.entity.InsuranceCoverageEntity;
import com.yuexunit.finance.project.entity.InsuranceEntity;
import com.yuexunit.finance.project.entity.LoanNoticeEntity;
import com.yuexunit.finance.project.entity.SupervisionEndallEntity;
import com.yuexunit.finance.project.entity.lexicon.ApiFinanceStateEnum;
import com.yuexunit.finance.project.entity.lexicon.ApiTypeEnum;
import com.yuexunit.finance.project.entity.lexicon.BeneficiaryMethodEnum;
import com.yuexunit.finance.project.entity.lexicon.BillingMethodEnum;
import com.yuexunit.finance.project.entity.lexicon.BulkstockSourceEnum;
import com.yuexunit.finance.project.entity.lexicon.ConstractStateEnum;
import com.yuexunit.finance.project.entity.lexicon.ContainerSourceEnum;
import com.yuexunit.finance.project.entity.lexicon.FileSignStateEnum;
import com.yuexunit.finance.project.entity.lexicon.FinanceAuditEnum;
import com.yuexunit.finance.project.entity.lexicon.FinanceSegmentEnum;
import com.yuexunit.finance.project.entity.lexicon.FinanceStateEnum;
import com.yuexunit.finance.project.entity.lexicon.OperatorRoleEnum;
import com.yuexunit.finance.project.entity.lexicon.ProductStateEnum;
import com.yuexunit.finance.project.entity.lexicon.ProductTypeEnum;
import com.yuexunit.finance.project.entity.lexicon.StatementStateEnum;
import com.yuexunit.finance.project.entity.lexicon.SupervisionStateEnum;
import com.yuexunit.finance.project.service.CommissionExtractApplicationService;
import com.yuexunit.finance.project.service.FinanceAuditLogService;
import com.yuexunit.finance.project.service.FinanceAuditService;
import com.yuexunit.finance.project.service.FinanceCommissionInfoService;
import com.yuexunit.finance.project.service.FinanceContainerLogService;
import com.yuexunit.finance.project.service.FinanceCutLinesService;
import com.yuexunit.finance.project.service.FinanceExpenseDetailService;
import com.yuexunit.finance.project.service.FinanceFilesInfoService;
import com.yuexunit.finance.project.service.FinanceLockedInfoService;
import com.yuexunit.finance.project.service.FinanceProductInnerService;
import com.yuexunit.finance.project.service.FinanceProductInterestItemService;
import com.yuexunit.finance.project.service.FinanceProductService;
import com.yuexunit.finance.project.service.FreightInfoService;
import com.yuexunit.finance.project.service.InsuranceCoverageBulkstockService;
import com.yuexunit.finance.project.service.InsuranceCoverageService;
import com.yuexunit.finance.project.service.InsuranceService;
import com.yuexunit.finance.support.FinanceInquireParams;
import com.yuexunit.finance.system.action.v1.dto.SendLetterMessage;
import com.yuexunit.finance.system.entity.SignFileInfoEntity;
import com.yuexunit.finance.system.service.SignFileInfoService;
import com.yuexunit.finance.tatistics.entity.StatisticsEndallEntity;
import com.yuexunit.finance.tatistics.service.StatisticsEndallService;
import com.yuexunit.finance.thread.EnterpriseSummaryTimeTask;
import com.yuexunit.fs.parse.service.FileParseService;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.inject.annotation.Implements;
import com.yuexunit.jsonutil.JSON;
import com.yuexunit.page.PageCriteria;
import com.yuexunit.page.PageList;
import com.yuexunit.permission.action.PermissionActionsApi;
import com.yuexunit.permission.action.dto.RoleListDto;
import com.yuexunit.persist.annotation.Transactional;
import com.yuexunit.persist.hibernate.SessionRepository;
import com.yuexunit.util.DateUtil;
import com.yuexunit.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @ClassName: FinanceApplicationActionApiImpl
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author chenxy
 * @date 2015年9月26日 下午12:14:15
 */
@Implements(FinanceApplicationActionApi.class)
public class FinanceApplicationActionApiImpl extends FinanceBaseAction implements FinanceApplicationActionApi {

	private static Logger logger = LoggerFactory.getLogger(FinanceApplicationActionApiImpl.class);

	private MaterialTemplateService materialTemplateService = ComponentFactory.loadClass(MaterialTemplateService.class);

	private StatisticsEndallService statisticsEndallService = ComponentFactory.loadClass(StatisticsEndallService.class);

	private InsuranceService insuranceService = ComponentFactory.loadClass(InsuranceService.class);

	private InsuranceCoverageService insuranceCoverageService = ComponentFactory.loadClass(InsuranceCoverageService.class);

	private InsuranceCoverageBulkstockService insuranceCoverageBulkstockService = ComponentFactory.loadClass(InsuranceCoverageBulkstockService.class);

	private FinanceProductService financeProductService = ComponentFactory.loadClass(FinanceProductService.class);

	private EnterpriseGradeService enterpriseGradeService = ComponentFactory.loadClass(EnterpriseGradeService.class);

	private FinanceAuditService financeAuditService = ComponentFactory.loadClass(FinanceAuditService.class);

	private FinanceCutLinesService financeCutLinesService = ComponentFactory.loadClass(FinanceCutLinesService.class);

	private TemporaryCreditLineService temporaryCreditLineService = ComponentFactory.loadClass(TemporaryCreditLineService.class);

	private FinanceCommissionInfoService financeCommissionInfoService = ComponentFactory.loadClass(FinanceCommissionInfoService.class);

	private FinanceExpenseDetailService financeExpenseDetailService = ComponentFactory.loadClass(FinanceExpenseDetailService.class);

	private EnterpriseCodeService enterpriseCodeService = ComponentFactory.loadClass(EnterpriseCodeService.class);

	private CommissionExtractApplicationService commissionExtractApplicationService = ComponentFactory.loadClass(CommissionExtractApplicationService.class);

	private FinanceBulkstockPledgeRateService financeBulkstockPledgeRateService = ComponentFactory.loadClass(FinanceBulkstockPledgeRateService.class);

	private SupplierCommissionGradeService supplierCommissionGradeService = ComponentFactory.loadClass(SupplierCommissionGradeService.class);

	private FinanceProductInnerService financeProductInnerService = ComponentFactory.loadClass(FinanceProductInnerService.class);

	private FinanceProductInterestItemService financeProductInterestItemService = ComponentFactory.loadClass(FinanceProductInterestItemService.class);

	private FinanceAuditLogService financeAuditLogService = ComponentFactory.loadClass(FinanceAuditLogService.class);

	private PermissionActionsApi permissionAction = ComponentFactory.loadClass(PermissionActionsApi.class);

	private EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);

	private AccountService accountService = ComponentFactory.loadClass(AccountService.class);

	private FinanceCancelApplicationService financeCancelApplicationService = ComponentFactory.loadClass(FinanceCancelApplicationService.class);

	private FinanceContainerLogService financeContainerLogService = ComponentFactory.loadClass(FinanceContainerLogService.class);

	private CommissionScaleTableService commissionScaleTableService = ComponentFactory.loadClass(CommissionScaleTableService.class);

	private FinanceFilesInfoService financeFilesInfoService = ComponentFactory.loadClass(FinanceFilesInfoService.class);

	private FreightInfoService freightInfoService = ComponentFactory.loadClass(FreightInfoService.class);

	private LogisticsCompanyService logisticsCompanyService = ComponentFactory.loadClass(LogisticsCompanyService.class);

	private SupplierService supplierService = ComponentFactory.loadClass(SupplierService.class);

	private FinanceLockedInfoService financeLockedInfoService = ComponentFactory.loadClass(FinanceLockedInfoService.class);

	private SignFileInfoService signFileInfoService = ComponentFactory.loadClass(SignFileInfoService.class);

	private FinanceApplicationActionApi financeApplicationActionApi = ComponentFactory.loadClass(FinanceApplicationActionApi.class);
	
	private String tmp = "客户(%s)融资(%s)目前处于融资审核环节对应的(%s)节点，请及时审批！";

	private String tmp1 = "客户(%s)融资(%s)目前处(%s)环节，请及时处理！";
	
	private String tmp2 = "客户(%s)融资(%s)目前处于放款审批环节对应的(%s)节点，请及时审批！";

	private static List<String> FREIGHT_TITLE = Arrays.asList(new String[] { "船舶", "运单号", "箱号", "箱型", "门点地址", "结算价", "结算对象", "备注", "确认时间", "结算日" });

	private void createFinanceMaterial(String materials, Long financeId, Long segmentId, FinanceSegmentEnum financeSegment) {
		List<FinanceMaterialEntity> materialList = financeMaterialService.inquireFinanceMaterialList(financeId, segmentId, financeSegment);
		Set<String> materialUuids = new HashSet<>();
		org.apache.commons.collections.CollectionUtils.addAll(materialUuids, materials.split(","));
		for (FinanceMaterialEntity me : materialList) {
			if (materialUuids.contains(me.getFileUuid())) {
				materialUuids.remove(me.getFileUuid());
			} else {
				financeMaterialService.deleteFinanceMaterial(me.getMaterialId());
			}
		}
		List<FinanceMaterialEntity> financeMaterialList = FinanceMaterialCastor.fromFinanceMaterialArray(financeId, segmentId, financeSegment, materialUuids.toArray(new String[materialUuids.size()]));
		for (FinanceMaterialEntity me : financeMaterialList) {
			financeMaterialService.createFinanceMaterial(me);
		}
	}

	@Transactional
	@Override
	public String createFinanceApplication(FinanceApplication params) {
		if (params.getEnterpriseInsurance() == null) {
			params.setEnterpriseInsurance(Boolean.FALSE);
		}

		//运费保理没有投保
		if (params.getProductType() != 4 && params.getEnterpriseInsurance() && (StringUtils.isBlank(params.getEnterpriseInsurer()) || StringUtils.isBlank(params.getEnterpriseInsuranceType()) || params.getEnterpriseInsuranceAmount() == null || params.getEnterpriseForceAmount() == null)) {
			throw new BusinessException("投保情况下,保单相关信息都不允许为空");
		}

		EnterpriseEntity enterprise = null;
		EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);

		enterprise = enterpriseService.inquireEnterprise(FinanceSessionContext.getEnterpriseId());

		EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(enterprise.getEnterpriseId());
		
		if (DateUtil.todayInt() > grade.getEffectiveEndDate()) {
			throw new BusinessException("授信已过期");
		}

		//判断是否有权限做该货品融资
		if(params.getBulkstockInfoIds()!=null && params.getBulkstockInfoIds().length>0){
			for(int i=0; i<params.getBulkstockInfoIds().length; i++) {
				BulkstockInfoEntity bie = bulkstockInfoService.inquireBulkstockInfo(params.getBulkstockInfoIds()[i]);
				FinanceBulkstockPledgeRateEntity fbpre = financeBulkstockPledgeRateService.inquireFinanceBulkstockPledgeRate(grade.getGradeEvaluationId(), bie.getBulkstockInfoId(), ProductTypeEnum.valueOf(params.getProductType()));
				if (fbpre == null) {
					throw new BusinessException("该用户不能做该货品融资或产品已过期!");
				}
			}
		}

		if (enterprise == null || (AuditStateEnum.PASS != enterprise.getAuditState() && AuditStateEnum.FINISH != enterprise.getAuditState())) {
			throw new BusinessException("企业还未通过平台审核,请等待审核通过后操作");
		}

		if (enterprise.getFreeze() != null && enterprise.getFreeze()) {
			throw new BusinessException("该企业已被冻结，不能发起融资申请！");
		}

		TemporaryCreditLineEntity temporary = temporaryCreditLineService.inquireTemporaryCreditLine(enterprise.getEnterpriseId());
		if (temporary == null) {
			temporary = new TemporaryCreditLineEntity();
			temporary.setTemporaryCreditline(BigDecimal.ZERO);
			temporary.setTemporaryCreditlineAlready(BigDecimal.ZERO);
		}

		BigDecimal remaining = grade.getCreditLine().subtract(grade.getCreditAlready()).add(temporary.getTemporaryCreditline().subtract(temporary.getTemporaryCreditlineAlready()));
		if (params.getApplicationAmount().compareTo(remaining) > 0) {
			throw new BusinessException("该企业授信额度不足！");
		}

		FinanceApplicationEntity financeEntity = FinanceApplicationCastor.fromFinanceApplication(params);
		financeEntity.setProductType(ProductTypeEnum.valueOf(params.getProductType()));
		financeEntity.setApplicationCreateDatetime(DateUtil.now());
		if (FinanceSessionContext.getAppKey().equals(FinanceConstant.APPKEY_ENTERPRISE_IOS) || FinanceSessionContext.getAppKey().equals(FinanceConstant.APPKEY_ENTERPRISE_ANDROID)) {
			//手机端创建直接提交
			financeEntity.setFinanceState(FinanceStateEnum.APPROVE);
		} else {
			financeEntity.setFinanceState(FinanceStateEnum.UNSUMIT);
		}
		Long financeId = financeApplicationService.createFinanceApplication(financeEntity);

		List<FinanceContainerBillEntity> financeContainerBills = FinanceApplicationCastor.fromFinanceApplicationContainerBill(params);
		// 订舱信息
		if (financeEntity.getBookingSpace()) {
			Integer caseQuantities = 0;
			if (params.getQuantity() != null) {
				for (Integer q : params.getQuantity()) {
					caseQuantities += q;
				}
			}
			FinanceContainerEntity financeContainer = financeEntity.getFinanceContainer();
			financeContainer.setFinanceId(financeId);
			financeContainer.setFinanceNumber(financeEntity.getFinanceNumber());
			financeContainer.setCaseQuantity(caseQuantities);
			financeContainer.setBookingSpaceNumber(params.getBookingSpaceNumber());
			financeContainerService.createFinanceContainer(financeContainer);
		}
		for (FinanceContainerBillEntity fcbe : financeContainerBills) {
			fcbe.setFinanceId(financeId);
			fcbe.setContainerSource(ContainerSourceEnum.ENTERPRISE);
			financeContainerBillService.createFinanceContainerBill(fcbe);
		}

		List<FinanceBulkstockEntity> financeBulkstockEntities = BulkstockCastor.fromFinanceApplication(params, financeId);
		for (FinanceBulkstockEntity entity : financeBulkstockEntities) {
			BulkstockInfoEntity be = bulkstockInfoService.inquireBulkstockInfo(entity.getBulkstockInfoId());
			if (be.getMeasurement() == MeasurementEnum.VOLUME) {
				if (entity.getVolume() == null) {
					throw new BusinessException("体积不能为空");
				}
			}

			financeBulkstockService.createFinanceBulkstockEntity(entity);
			FinanceBulkstockColdStorageEntity bulkstockColdStorage = entity.getBulkstockColdStorage();
			FinanceBulkstockDangerousEntity bulkstockDangerous = entity.getBulkstockDangerous();
			if (bulkstockColdStorage != null) {
				bulkstockColdStorage.setBulkstockId(entity.getBulkstockId());
				financeBulkstockColdStorageService.createFinanceBulkstockColdStorage(bulkstockColdStorage);
			}
			if (bulkstockDangerous != null) {
				bulkstockDangerous.setBulkstockId(entity.getBulkstockId());
				financeBulkstockDangerousService.createFinanceBulkstockDangerous(bulkstockDangerous);
			}
		}

		//保存运单号
		if (StringUtil.isNotBlank(params.getWaybillNumber())) {
			FinanceContainerWaybillEntity entity = new FinanceContainerWaybillEntity();
			entity.setFinanceId(financeId);
			entity.setFinanceNumber(financeEntity.getFinanceNumber());
			entity.setEnterpriseId(financeEntity.getEnterpriseId());
			entity.setEnterpriseName(financeEntity.getEnterpriseName());
			entity.setWaybillNumber(params.getWaybillNumber());
			financeContainerWaybillService.createFinanceContainerWaybill(entity);
		}

		// 项目动态
		FinanceProcessEntity financeProcessEntity = FinanceProcessCastor.fromFinanceSubmitProcess(financeId, financeEntity.getFinanceNumber());
		financeProcessService.createFinanceProcess(financeProcessEntity);

		//消息通知
		if (FinanceStateEnum.APPROVE == financeEntity.getFinanceState()) {
			SendLetterMessage.sendLetterMessage("businessAuditState", "有新的融资审批意见未填写，请及时查看!");
		}

		if (params.getProductType() == 4) {
			LogisticsCompanyEntity lce = logisticsCompanyService.inquireLogisticsCompanyByCompanyName(params.getDeliver());
			if (lce == null) {
				throw new BusinessException("请输入系统中存在的名称!");
			}

			//运费信息
			if (params.getCaseNumbers() != null) {
				for (int i = 0; i < params.getCaseNumbers().length; i++) {
					ContainerInventoryEntity cie = new ContainerInventoryEntity();
					cie.setFinanceId(financeId);
					cie.setFinanceNumber(financeEntity.getFinanceNumber());
					cie.setEnterpriseId(financeEntity.getEnterpriseId());
					cie.setEnterpriseName(financeEntity.getEnterpriseName());
					cie.setContainerSource(BulkstockSourceEnum.FINANCE);
					cie.setWaybillNumber(params.getWaybillNumbers()[i]);
					cie.setCaseNumber(params.getCaseNumbers()[i]);
					cie.setCaseSize(params.getCaseSizes()[i]);
					cie.setAbnormal(Boolean.TRUE);
					cie.setShipsName(params.getShipNames()[i]);
					cie.setSettlementDate(params.getSettlementDates()[i]);
					cie.setEnabled(Boolean.TRUE);
					cie.setType(2);
					cie.setDoorsAdress(params.getDoorsAdresses()[i]);
					cie.setSettlementObject(params.getSettlementObjects()[i]);
					cie.setSettlementPrice(params.getSettlementPrices()[i]);
					cie.setRemark(params.getRemarks()[i]);
					cie.setConfrimDate(params.getConfirmDates()[i]);
					containerInventoryService.createContainerInventory(cie);
				}
			}

			//发票信息
			for (int i = 0; i < params.getFreightNum().length; i++) {
				FreightInfoEntity fie = new FreightInfoEntity();
				fie.setFinanceId(financeId);
				fie.setDueDate(params.getDueDate()[i]);
				fie.setFactoringAmount(params.getFactoringAmount()[i]);
				fie.setInvoiceAmount(params.getInvoiceAmount()[i]);
				fie.setInvoiceDate(params.getInvoiceDate()[i]);
				fie.setInvoiceNumber(params.getInvoiceNumber()[i]);
				fie.setOthersRemark(params.getOthersRemark()[i]);
				fie.setPurchaser(params.getPurchaser()[i]);
				fie.setReceivableAmount(params.getReceivableAmount()[i]);
				fie.setFileUuid(params.getFileUuid()[i]);
				freightInfoService.createFreightInfo(fie);

				ContainerInventoryEntity cie = new ContainerInventoryEntity();
				BeanUtils.copyProperties(fie, cie);
				cie.setFinanceId(financeId);
				cie.setFinanceNumber(financeEntity.getFinanceNumber());
				cie.setEnterpriseId(financeEntity.getEnterpriseId());
				cie.setEnterpriseName(financeEntity.getEnterpriseName());
				cie.setContainerSource(BulkstockSourceEnum.FINANCE);
				cie.setAbnormal(Boolean.TRUE);
				cie.setEnabled(Boolean.TRUE);
				cie.setType(3);
				cie.setSettlementPrice(fie.getInvoiceAmount());
				containerInventoryService.createContainerInventory(cie);
			}
		} else if (params.getProductType() == 1) {
			SupplierEntity supplier = supplierService.inquireSupplierDetail(params.getReceive());
			if (null == supplier) {
				throw new BusinessException("该供应商不存在，请先添加");
			}
		}

		return financeId.toString();
	}

	@Transactional
	@Override
	public String createFinanceApplicationNologin(FinanceApplication params) {
		FinanceProductEntity product = financeProductService.inquireFinanceProduct(params.getProductId());
		if (ProductStateEnum.PUBLISHED != product.getState()) {
			throw new BusinessException("该融资产品未生效或者已经过期");
		}

		if (params.getEnterpriseInsurance()
				&& (StringUtils.isBlank(params.getEnterpriseInsurer()) || StringUtils.isBlank(params.getEnterpriseInsuranceType()) || params.getEnterpriseInsuranceAmount() == null || params.getEnterpriseForceAmount() == null)) {
			throw new BusinessException("投保情况下,保单相关信息都不允许为空");
		}

		EnterpriseEntity enterprise = null;
		EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);

		if (StringUtil.isNotBlank(params.getFingerTrunkAccountId())) {
			FingerTrunkAccountMappingService fingerService = ComponentFactory.loadClass(FingerTrunkAccountMappingService.class);
			FingerTrunkAccountMappingEntity ftame = fingerService.inquireFingerTrunkAccountMappingDetail(params.getFingerTrunkAccountId());
			enterprise = enterpriseService.inquireEnterpriseFromAccountId(ftame.getFinanceAccountId());
		}

		if (enterprise == null || AuditStateEnum.PASS != enterprise.getAuditState()) {
			throw new BusinessException("企业还未通过平台审核,请等待审核通过后操作");
		}

		if (enterprise.getFreeze()) {
			throw new BusinessException("该企业已被冻结，不能发起融资申请！");
		}

		EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(enterprise.getEnterpriseId());
		BigDecimal remaining = grade.getCreditLine().subtract(grade.getCreditAlready());
		if (params.getApplicationAmount().compareTo(remaining) > 0) {
			throw new BusinessException("授信额度不足！");
		}

		FinanceApplicationEntity financeEntity = FinanceApplicationCastor.fromFinanceApplication(params);
		financeEntity.setProductType(product.getProductType());
		financeEntity.setApplicationCreateDatetime(DateUtil.now());
		Long financeId = financeApplicationService.createFinanceApplication(financeEntity);

		List<FinanceContainerBillEntity> financeContainerBills = FinanceApplicationCastor.fromFinanceApplicationContainerBill(params);
		// 订舱信息
		if (financeEntity.getBookingSpace()) {
			Integer caseQuantities = 0;
			if (params.getQuantity() != null) {
				for (Integer q : params.getQuantity()) {
					caseQuantities += q;
				}
			}
			FinanceContainerEntity financeContainer = financeEntity.getFinanceContainer();
			financeContainer.setFinanceId(financeId);
			financeContainer.setFinanceNumber(financeEntity.getFinanceNumber());
			financeContainer.setCaseQuantity(caseQuantities);
			financeContainer.setBookingSpaceNumber(params.getBookingSpaceNumber());
			financeContainerService.createFinanceContainer(financeContainer);
		}
		for (FinanceContainerBillEntity fcbe : financeContainerBills) {
			fcbe.setFinanceId(financeId);
			fcbe.setContainerSource(ContainerSourceEnum.ENTERPRISE);
			financeContainerBillService.createFinanceContainerBill(fcbe);
		}

		List<FinanceBulkstockEntity> financeBulkstockEntities = BulkstockCastor.fromFinanceApplication(params, financeId);
		for (FinanceBulkstockEntity entity : financeBulkstockEntities) {
			BulkstockInfoEntity be = bulkstockInfoService.inquireBulkstockInfo(entity.getBulkstockInfoId());
			if (be.getMeasurement() == MeasurementEnum.VOLUME) {
				if (entity.getVolume() == null) {
					throw new BusinessException("体积不能为空");
				}
			}

			financeBulkstockService.createFinanceBulkstockEntity(entity);
			FinanceBulkstockColdStorageEntity bulkstockColdStorage = entity.getBulkstockColdStorage();
			FinanceBulkstockDangerousEntity bulkstockDangerous = entity.getBulkstockDangerous();
			if (bulkstockColdStorage != null) {
				bulkstockColdStorage.setBulkstockId(entity.getBulkstockId());
				financeBulkstockColdStorageService.createFinanceBulkstockColdStorage(bulkstockColdStorage);
			}
			if (bulkstockDangerous != null) {
				bulkstockDangerous.setBulkstockId(entity.getBulkstockId());
				financeBulkstockDangerousService.createFinanceBulkstockDangerous(bulkstockDangerous);
			}
		}
		// 项目动态
		FinanceProcessEntity financeProcessEntity = FinanceProcessCastor.fromFinanceSubmitProcess(financeId, financeEntity.getFinanceNumber());
		financeProcessService.createFinanceProcess(financeProcessEntity);
		return financeId.toString();
	}

	@Transactional
	@Override
	public void updateFinanceApplication(FinanceApplicationUpdate params) {
		FinanceApplicationEntity financePersist = financeApplicationService.inquireFinanceApplicationEntity(params.getFinanceId());
		if (FinanceStateEnum.UNSUMIT != financePersist.getFinanceState() && FinanceStateEnum.APPROVE_NOPASS != financePersist.getFinanceState() && FinanceStateEnum.APPROVE_NOPASS != financePersist.getFinanceState()) {
			throw new BusinessException("只能修改待提交或未通过的融资申请");
		}

		EnterpriseEntity enterprise = null;
		EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);

		enterprise = enterpriseService.inquireEnterprise(FinanceSessionContext.getEnterpriseId());

		EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(enterprise.getEnterpriseId());
		for(int i=0; i<params.getBulkstockInfoIds().length; i++) {
			FinanceBulkstockPledgeRateEntity fbpre = financeBulkstockPledgeRateService.inquireFinanceBulkstockPledgeRate(grade.getGradeEvaluationId(), params.getBulkstockInfoIds()[i], ProductTypeEnum.valueOf(params.getProductType()));
			if (fbpre == null) {
				throw new BusinessException("该用户不能做该货品融资!");
			}
		}

		if (enterprise == null || (AuditStateEnum.PASS != enterprise.getAuditState() && AuditStateEnum.FINISH != enterprise.getAuditState())) {
			throw new BusinessException("企业还未通过平台审核,请等待审核通过后操作");
		}

		if (enterprise.getFreeze() != null && enterprise.getFreeze()) {
			throw new BusinessException("该企业已被冻结，不能发起融资申请！");
		}

		FinanceApplicationEntity financeEntity = FinanceApplicationCastor.fromFinanceApplication(params);
		financeEntity.setProductType(financePersist.getProductType());
		financeEntity.setFinanceId(params.getFinanceId());
		financeEntity.setFinanceState(FinanceStateEnum.UNSUMIT);
		financeApplicationService.updateFinanceApplication(financeEntity);
		Long financeId = financeEntity.getFinanceId();
		// 订舱信息
		if (financeEntity.getBookingSpace()) {
			FinanceContainerEntity financeContainer = financeContainerService.inquireFinanceContainer(financeId);
			if (financeContainer == null) {
				financeContainer = financeEntity.getFinanceContainer();
				financeContainer.setFinanceId(financeId);
				financeContainer.setFinanceNumber(financeEntity.getFinanceNumber());
				financeContainerService.createFinanceContainer(financeContainer);
			} else {
				BeanUtils.copyProperties(financeEntity.getFinanceContainer(), financeContainer);
				financeContainerService.renovateFinanceContainer(financeContainer);
			}
		}
		List<FinanceContainerBillEntity> containerBills = financeContainerBillService.inquireFinanceContainerBillList(financeId);
		for (FinanceContainerBillEntity fcbe : containerBills) {
			financeContainerBillService.deleteFinanceContainerBill(fcbe);
		}
		List<FinanceContainerBillEntity> financeContainerBills = FinanceApplicationCastor.fromFinanceApplicationContainerBill(params);
		for (FinanceContainerBillEntity fcbe : financeContainerBills) {
			fcbe.setFinanceId(financeId);
			financeContainerBillService.createFinanceContainerBill(fcbe);
		}

		// 融资货物信息处理
		List<FinanceBulkstockColdStorageEntity> coldStorages = financeBulkstockColdStorageService.inquireFinanceBulkstockColdStorageList(financeId);
		for (FinanceBulkstockColdStorageEntity coldStorage : coldStorages) {
			financeBulkstockColdStorageService.deleteFinanceBulkstockColdStorage(coldStorage);
		}
		List<FinanceBulkstockDangerousEntity> dangerouses = financeBulkstockDangerousService.inquireFinanceBulkstockDangerousList(financeId);
		for (FinanceBulkstockDangerousEntity dangerous : dangerouses) {
			financeBulkstockDangerousService.deleteFinanceBulkstockDangerous(dangerous);
		}

		List<FinanceBulkstockEntity> cpersists = financeBulkstockService.inquireFinanceBulkstockList(params.getFinanceId());
		List<FinanceBulkstockEntity> centities = BulkstockCastor.fromFinanceApplication(params, params.getFinanceId());
		Set<Long> bulkstockIdSet = CollectionUtils.convertSet(params.getBulkstockIds());
		for (int i = 0; i < centities.size(); i++) {
			FinanceBulkstockEntity fce = centities.get(i);
			fce.setBulkstockId(params.getBulkstockIds()[i]);
			if (!LongUtils.isPrimaryKey(fce.getBulkstockId())) {
				financeBulkstockService.createFinanceBulkstockEntity(fce);
			} else {
				financeBulkstockService.updateFinanceBulkstockEntity(fce);
			}

			FinanceBulkstockColdStorageEntity bulkstockColdStorage = fce.getBulkstockColdStorage();
			FinanceBulkstockDangerousEntity bulkstockDangerous = fce.getBulkstockDangerous();
			if (bulkstockColdStorage != null) {
				bulkstockColdStorage.setBulkstockId(fce.getBulkstockId());
				financeBulkstockColdStorageService.createFinanceBulkstockColdStorage(bulkstockColdStorage);
			}
			if (bulkstockDangerous != null) {
				bulkstockDangerous.setBulkstockId(fce.getBulkstockId());
				financeBulkstockDangerousService.createFinanceBulkstockDangerous(bulkstockDangerous);
			}
		}
		for (FinanceBulkstockEntity c : cpersists) {
			if (!bulkstockIdSet.contains(c.getBulkstockId())) {
				financeBulkstockService.deleteFinanceBulkstockEntity(c.getBulkstockId());
			}
		}
	}

	@Transactional
	@Override
	public void supplementFinanceEvidentiary(Long financeId, Long[] evidentiaryCategoryIds, Long[] templateIds, String[] templateNames, Long[] evidentiaryIds, String[] materialFileuuids) {
		FinanceApplicationEntity financePersist = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		MaterialTemplateEnum[] checkedRequireds = new MaterialTemplateEnum[templateIds.length];
		List<MaterialTemplateEntity> templates = materialTemplateService.inquireMaterialTemplateList(financePersist.getBulkstockCategoryId());
		for (MaterialTemplateEntity template : templates) {
			boolean templateMaterial = false; // 是否提交材料模版资料
			for (int i = 0; i < templateIds.length; i++) {
				Long templateId = templateIds[i];
				if (template.getTemplateId().equals(templateId)) {
					checkedRequireds[i] = template.getCheckedRequired();
					templateMaterial = true;
					break;
				}
			}
			if (!templateMaterial) { // 未提交资料模版
				FinanceEvidentiaryCategoryEntity categoryEntity = financeEvidentiaryCategoryService.inquireFinanceEvidentiaryCategory(financeId, template.getTemplateId());
				if (categoryEntity == null) {
					categoryEntity = new FinanceEvidentiaryCategoryEntity();
					categoryEntity.setFinanceId(financeId);
					categoryEntity.setTemplateId(template.getTemplateId());
					categoryEntity.setCheckedRequired(template.getCheckedRequired());
					categoryEntity.setTemplateName(template.getTemplateName());
					financeEvidentiaryCategoryService.createEvidentiaryCategory(categoryEntity);
				}
			}
		}

		List<FinanceEvidentiaryEntity> persistis = financeEvidentiaryService.inquireEvidentiaryList(financeId);
		Set<Long> evidentiaryIdSet = CollectionUtils.convertSet(evidentiaryIds);
		for (int i = 0; i < evidentiaryCategoryIds.length; i++) {
			FinanceEvidentiaryCategoryEntity categoryEntity = financeEvidentiaryCategoryService.inquireFinanceEvidentiaryCategory(financeId, templateIds[i]);
			if (categoryEntity == null) {
				categoryEntity = new FinanceEvidentiaryCategoryEntity();
				categoryEntity.setFinanceId(financeId);
				categoryEntity.setTemplateId(templateIds[i]);
				categoryEntity.setTemplateName(templateNames[i]);
				categoryEntity.setCheckedRequired(checkedRequireds[i]);
				financeEvidentiaryCategoryService.createEvidentiaryCategory(categoryEntity);
			}
			Long evidentiaryCategoryId = categoryEntity.getEvidentiaryCategoryId();
			FinanceEvidentiaryEntity entity = new FinanceEvidentiaryEntity();
			entity.setEvidentiaryId(evidentiaryIds[i]);
			entity.setEvidentiaryCategoryId(evidentiaryCategoryId);
			entity.setFinanceId(financeId);
			entity.setMaterialFileuuid(materialFileuuids[i]);
			if (!LongUtils.isPrimaryKey(entity.getEvidentiaryId())) {
				financeEvidentiaryService.createEvidentiary(entity);
			} else {
				financeEvidentiaryService.updateEvidentiary(entity);
			}
		}
		for (FinanceEvidentiaryEntity p: persistis) {
			if (!evidentiaryIdSet.contains(p.getEvidentiaryId())) {
				financeEvidentiaryService.deleteEvidentiary(p.getEvidentiaryId());
			}
		}
	}

	@Transactional
	@Override
	public void readFinanceEvidentiary(Long evidentiaryId) {
		FinanceEvidentiaryEntity persist = financeEvidentiaryService.inquireEvidentiary(evidentiaryId);
		persist.setReader(FinanceSessionContext.getAccountFullName());
		persist.setReadFlag(Boolean.TRUE);
		financeEvidentiaryService.updateEvidentiary(persist);
	}

	@Transactional
	@Override
	public void cancelFinanceApplication(Long financeId) {
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		if (FinanceStateEnum.APPROVE_NOPASS != financeEntity.getFinanceState() && FinanceStateEnum.UNSUMIT != financeEntity.getFinanceState() && FinanceStateEnum.WAIT_CONFIRM != financeEntity.getFinanceState()) {
			throw new BusinessException("只能取消审批中（未通过/待确认/待确认）的融资申请");
		}
		financeEntity.setFinanceState(FinanceStateEnum.CANCEL);
		financeApplicationService.renovateFinanceApplication(financeEntity);

		// 项目动态
		FinanceProcessEntity financeProcessEntity = FinanceProcessCastor.fromFinanceSubmitProcess(financeId, financeEntity.getFinanceNumber());
		financeProcessService.createFinanceProcess(financeProcessEntity);
	}

	private FinanceAuditEntity auditFinanceApplication(FinanceAudit financeAudit, FinanceApplicationEntity persist, FinanceAuditEntity audit) {
		if (FinanceStateEnum.APPROVE != persist.getFinanceState() && FinanceStateEnum.WAIT_APPROVE != persist.getFinanceState()) {
			throw new BusinessException("不可操作,只能对处于审批状态中的融资申请进行操作");
		}
		FinanceAuditEntity auditEntity = FinanceApplicationCastor.fromFinanceAudit(financeAudit, audit);
		auditEntity.setFinanceNumber(persist.getFinanceNumber());
		auditEntity.setFinanceAuditState(FinanceAuditEnum.COMPLETED);
		if (auditEntity.getFinanceAuditId() != null) {
			financeAuditService.updateFinanceAuditEntity(auditEntity);
		} else {
			financeAuditService.createFinanceAuditEntity(auditEntity);
		}

		persist.setFinanceAmount(auditEntity.getFinanceAmount());
		persist.setAuditInterest(auditEntity.getAuditInterest());
		persist.setAuditRemark(auditEntity.getAuditRemark());
		persist.setAuditorId(auditEntity.getAuditorId());
		persist.setAuditor(auditEntity.getAuditor());

		BigDecimal financeAmount = persist.getFinanceAmount();
		BigDecimal evaluateAmount = BigDecimal.ZERO;

		List<FinanceBulkstockEntity> bulkstocks = new ArrayList<>();
		//		if(financeAudit.getBulkstockIds()!=null){
		//			for (int i = 0; i < financeAudit.getBulkstockIds().length; i++) {
		//				Long bulkstockId = financeAudit.getBulkstockIds()[i];
		//				FinanceBulkstockEntity bulkstock = financeBulkstockService.inquireFinanceBulkstock(bulkstockId);
		//				bulkstock.setEvaluatePrice(CollectionUtils.getArrayIndexValue(financeAudit.getEvaluatePrice(), i));
		//				bulkstock.setHighestPrice(CollectionUtils.getArrayIndexValue(financeAudit.getHighestPrice(), i));
		//				bulkstock.setLowestPrice(CollectionUtils.getArrayIndexValue(financeAudit.getLowestPrice(), i));
		//				evaluateAmount = evaluateAmount.add(bulkstock.getEvaluatePrice().multiply(bulkstock.getValuationQuantity()));
		//				bulkstocks.add(bulkstock);
		//			}
		//		}
		for (FinanceBulkstockEntity bulkstock : bulkstocks) {
			bulkstock.setFinancePrice(bulkstock.getEvaluatePrice().multiply(financeAmount).divide(evaluateAmount, 2, RoundingMode.HALF_UP)); // 融资单价=估值单价/全部货物估值总额*融资金额
			// (保留两位小数)
			financeBulkstockService.renovateFinanceBulkstock(bulkstock); 

			List<ContainerBulkstockEntity> cbes = containerBulkstockService.inquireContainerBulkstockListByBulkstockId(bulkstock.getBulkstockId());
			for (ContainerBulkstockEntity cbe : cbes) {
				cbe.setFinancePrice(bulkstock.getFinancePrice());
				containerBulkstockService.updateContainerBulkstock(cbe);
			}
		}
		return auditEntity;
	}

	@Transactional
	@Override
	public void sendLetter(String title, String message, Long accountId) {
		FinanceLetterBlockingQueue.putPlatformFinanceLetter(accountId, title, "finance.application.unaudit", message);
	}

	@Transactional
	@Override
	public void sendLetter1() {
		FinanceLetterBlockingQueue.putEnterpriseFinanceLetter(FinanceSessionContext.getEnterpriseId(), "测试消息", "finance.application.approved", "TEST-001");
	}

	@Override
	public void testSummayry() {
		EnterpriseSummaryTimeTask task = new EnterpriseSummaryTimeTask();
		task.run1();
	}

	@Override
	public void handleCountDaysInterest(String enterpriseName, String financeNumber, Integer date) {
		EnterpriseSummaryTimeTask task = new EnterpriseSummaryTimeTask();
		task.autoCountDaysInterest(enterpriseName, financeNumber, date);
	}
	
	@Override
	@Transactional
	public void initEnterpriseEnterprise(Long enterpriseId) {
		EnterpriseSummaryTimeTask task = new EnterpriseSummaryTimeTask();
		task.initEnterpriseEnterprise(enterpriseId);
	}

	@Transactional
	@Override
	public String consentFinanceApplication(FinanceAudit financeAudit) {
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeAudit.getFinanceId());
		FinanceAuditEntity audit = financeAuditService.inquireLatestFinanceAudit(financeAudit.getFinanceId());
		logger.info("financeId:"+financeAudit.getFinanceId()+"---申请金额APPLICATION_AMOUNT:"+financeEntity.getApplicationAmount()+"----审批金额FINANCE_AMOUNT："+financeEntity.getFinanceAmount());
		EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(financeEntity.getEnterpriseId());
		TemporaryCreditLineEntity temporary = temporaryCreditLineService.inquireTemporaryCreditLine(financeEntity.getEnterpriseId());
		if (temporary == null) {
			temporary = new TemporaryCreditLineEntity();
			temporary.setTemporaryCreditline(BigDecimal.ZERO);
			temporary.setTemporaryCreditlineAlready(BigDecimal.ZERO);
		}

		BigDecimal remaining = grade.getCreditLine().subtract(grade.getCreditAlready()).add(temporary.getTemporaryCreditline());

		if (financeEntity.getFinanceAmount() != null&& financeEntity.getFinanceAmount().compareTo(remaining) > 0) {
			throw new BusinessException("该企业授信额度不足！");
		}
		financeEntity.setFinanceState(FinanceStateEnum.WAIT_LOAN);

		//仓储质押和运费保理跳过放款申请
		if (ProductTypeEnum.FREIGHT_FACTORING == financeEntity.getProductType() || ProductTypeEnum.MANIFEST_PLEDGE == financeEntity.getProductType() || ProductTypeEnum.PROXY_SALE == financeEntity.getProductType() || ProductTypeEnum.PURCHASING_STORAGE == financeEntity.getProductType()) {
			financeEntity.setFinanceState(FinanceStateEnum.WAIT_LOAN);
			LoanNoticeEntity ln = new LoanNoticeEntity();
			ln.setFinanceId(financeEntity.getFinanceId());
			ln.setFinanceNumber(financeEntity.getFinanceNumber());
			ln.setEnterpriseId(financeEntity.getEnterpriseId());
			ln.setEnterpriseName(financeEntity.getEnterpriseName());
			ln.setLoanMethod(BeneficiaryMethodEnum.TRANSFER);
			ln.setLoanDate(DateUtil.todayInt());
			ln.setLoanAmount(financeEntity.getFinanceAmount());
			ln.setLoanAmountAlready(BigDecimal.ZERO);
			ln.setBeneficiaryName(financeEntity.getEnterpriseName());
			ln.setOperator(FinanceSessionContext.getAccountFullName());
			ln.setOperatorId(FinanceSessionContext.getAccountId());

			List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
			StringBuffer sb = new StringBuffer();
			for (RoleListDto rlt : rl) {
				sb.append(rlt.getRoleName()).append(",");
			}
			sb.deleteCharAt(sb.length() - 1);

			ln.setApplyDepartment(sb.toString());
			ln.setApplyDate(DateUtil.now());
			ln.setFinalState(ApiFinanceStateEnum.ZJ.getCode());
			ln.setLeader2AuditState(Boolean.TRUE);
			ln.setFinancialLeaderAuditState(Boolean.TRUE);
			ln.setFinancialAuditState(Boolean.TRUE);
			ln.setAuditState2(Boolean.TRUE);
			ln.setAuditState1(Boolean.TRUE);
			ln.setLeader1AuditState(Boolean.TRUE);
			ln.setApplicant(audit.getBusinessAuditor());
			ln.setFinalState(ApiFinanceStateEnum.ZJ.getCode());

			loanNoticeService.createLoanNotice(ln);

			List<ContainerInventoryEntity> inventories = containerInventoryService.inquireSupervisionFinanceAmountList(financeEntity.getFinanceId());
			for (ContainerInventoryEntity cie : inventories) {
				cie.setLoanNoticeId(ln.getLoanNoticeId());
				containerInventoryService.updateContainerInventory(cie);
			}
			
			SendLetterMessage.sendLetterMessage("loanNoticeFinancialAudit_1", String.format(tmp2, financeEntity.getEnterpriseName(), financeEntity.getFinanceNumber(), "资金审核"));
		} else if ((financeEntity.getSettlementMethod() !=null && financeEntity.getSettlementMethod() == 2)) {
			financeEntity.setFinanceState(FinanceStateEnum.WAIT_LOAN);
			SupplierEntity supplier = supplierService.inquireSupplierDetail(financeEntity.getReceive());
			LoanNoticeEntity ln = new LoanNoticeEntity();
			ln.setFinanceId(financeEntity.getFinanceId());
			ln.setFinanceNumber(financeEntity.getFinanceNumber());
			ln.setEnterpriseId(supplier.getSupplierId());
			ln.setEnterpriseName(supplier.getSupplierName());
			ln.setLoanMethod(BeneficiaryMethodEnum.TRANSFER);
			ln.setLoanDate(DateUtil.todayInt());
			ln.setApplyDate(DateUtil.now());
			ln.setLoanAmount(financeEntity.getFinanceAmount());
			ln.setLoanAmountAlready(BigDecimal.ZERO);
			ln.setBeneficiaryName(financeEntity.getEnterpriseName());
			ln.setOperator(FinanceSessionContext.getAccountFullName());
			ln.setOperatorId(FinanceSessionContext.getAccountId());
			ln.setApplicant(audit.getBusinessAuditor());
			ln.setFinalState(ApiFinanceStateEnum.ZJ.getCode());

			loanNoticeService.createLoanNotice(ln);
			
			SendLetterMessage.sendLetterMessage("loanNoticeFinancialAudit_1", String.format(tmp2, financeEntity.getEnterpriseName(), financeEntity.getFinanceNumber(), "资金审核"));
		}

		financeEntity.setApplicationCreateDatetime(null);
		financeEntity.setConstractCreateDatetime(DateUtil.now());
		financeEntity.setAdvanceTimeLimit(0);
		financeEntity.setPunishTimeLimit(0);
		financeApplicationService.renovateFinanceApplication(financeEntity);

		// 发送消息
		FinanceLetterBlockingQueue.putEnterpriseFinanceLetter(financeEntity.getEnterpriseId(), "融资审批", "finance.application.approved", financeEntity.getFinanceNumber());
		// 项目动态
		FinanceProcessEntity financeProcessEntity = FinanceProcessCastor.fromFinanceAuditProcess(financeEntity.getFinanceId(), financeEntity.getFinanceNumber(), audit.getFinanceAuditId());
		financeProcessService.createFinanceProcess(financeProcessEntity);
		// 保证金生成 客户->平台 付款单
		//		if (audit.getBail() != null && audit.getBail().compareTo(BigDecimal.ZERO) > 0) {
		//			FinanceMoneyStatementEntity moneyEntity = FinanceLoanCastor.fromFinanceAuditBail(financeEntity, audit);
		//			financeMoneyStatementService.createFinanceMoneyStatement(moneyEntity);
		//		}
		// 生成平台保单信息
		if (Boolean.TRUE == audit.getInsurance()) {
			InsuranceEntity insurance = FinanceContractCastor.fromFinanceAudit(financeEntity, audit);
			insuranceService.createFinanceInsurance(insurance);

			InsuranceCoverageEntity coverage = FinanceContractCastor.fromFinanceAudit(insurance, audit);
			insuranceCoverageService.createInsuranceCoverage(coverage);

			List<InsuranceCoverageBulkstockEntity> bulkstocks = FinanceContractCastor.fromFinanceAudit(coverage, audit);
			for (InsuranceCoverageBulkstockEntity entity : bulkstocks) {
				insuranceCoverageBulkstockService.createInsuranceCoverageBulkstock(entity);
			}
		}
		// 生成企业保单信息
		if (financeEntity.getEnterpriseInsurance()) {
			InsuranceEntity insurance = FinanceContractCastor.fromFinanceApplicationEntity(financeEntity);
			insuranceService.createFinanceInsurance(insurance);

			InsuranceCoverageEntity coverage = FinanceContractCastor.fromFinanceApplicationEntity(insurance, financeEntity);
			insuranceCoverageService.createInsuranceCoverage(coverage);

			List<InsuranceCoverageBulkstockEntity> bulkstocks = FinanceContractCastor.fromFinanceApplicationEntity(coverage, financeEntity);
			for (InsuranceCoverageBulkstockEntity entity : bulkstocks) {
				insuranceCoverageBulkstockService.createInsuranceCoverageBulkstock(entity);
			}
		}

		//		if (financeEntity.getBookingSpace()) {
		//			FinanceContainerEntity fce = financeContainerService.inquireFinanceContainer(financeEntity.getFinanceId());
		//			FinanceApplicationActionApi financeApplicationActionApi = ComponentFactory.loadClass(FinanceApplicationActionApi.class);
		//			financeApplicationActionApi.changeOrderInfo(fce.getBookingSpaceNumber(), financeEntity.getFinanceNumber(), 1);
		//		}

		return audit.getFinanceAuditId().toString();
	}


	@Override
	@Transactional
	public void supplementFinanceProductInner(FinanceProductInnerInput input) {
		//生成产品信息
		FinanceProductInnerEntity productInner = financeProductInnerService.inquireFinanceProductInner(input.getFinanceId(), null);
		if (productInner == null) {
			productInner = new FinanceProductInnerEntity();
		}
		productInner.setProductType(ProductTypeEnum.valueOf(input.getProductType()));
		productInner.setInterest(input.getIntrerst());
		productInner.setFinanceDays(input.getFinanceDays());
		productInner.setCycle(input.getCycle());
		productInner.setFinanceId(input.getFinanceId());
		productInner.setEnterpriseId(input.getFinanceId());
		productInner.setBailRate(input.getBailRate());
		productInner.setDistrain(input.getDistrain());
		financeProductInnerService.createFinanceProductInner(productInner);

		List<FinanceProductInterestItemEntity> fpiies = financeProductInterestItemService.inquireFinanceProductInterestItemList(productInner.getFinanceProductId());
		for (FinanceProductInterestItemEntity fppie : fpiies) {
			financeProductInterestItemService.deleteFinanceProductInterestItem(fppie.getFinanceProductInterestItemId());
		}

		if(input.getFinanceProductInterestItemName()!=null){
			for (int i=0; i<input.getFinanceProductInterestItemName().length; i++) {
				FinanceProductInterestItemEntity interestItem = financeProductInterestItemService.inquireFinanceProductInterestItem(input.getFinanceProductInterestItemId()[i]);
				if (interestItem != null) {
					financeProductInterestItemService.deleteFinanceProductInterestItem(interestItem.getFinanceProductInterestItemId());
				}
				interestItem = new FinanceProductInterestItemEntity();
				interestItem.setFinanceProductInterestItemName(input.getFinanceProductInterestItemName()[i]);
				interestItem.setFinanceProductId(productInner.getFinanceProductId());
				interestItem.setStartDay(input.getStartDay()[i]);
				interestItem.setEndDay(input.getEndDay()[i]);
				interestItem.setAmout(input.getInterestRate()[i]);
				interestItem.setBillingMethod(BillingMethodEnum.valueOf(input.getBillingType()[i]));
				financeProductInterestItemService.createFinanceProductInterestItem(interestItem);
			}
		}
	}

	@Override
	@Transactional
	public FiananceAuditInfo supplementBussinessAuditOpinion(FinanceAudit financeAudit) {
		logger.info("2017-9-5 16:16:01", financeAudit.toString());
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeAudit.getFinanceId());
		if (financeEntity.getProductType().ordinal() == 1 || financeEntity.getProductType().ordinal() == 5) {
			if (StringUtil.isNotBlank(financeAudit.getBail()) && (new BigDecimal(financeAudit.getBail())).compareTo(BigDecimal.ZERO) <= 0) {
				throw new BusinessException("代采模式下，必须要有保证金！");
			}

			SupplierEntity supplier = supplierService.inquireSupplierDetail(financeEntity.getReceive());
			if (null == supplier) {
				throw new BusinessException("该供应商不存在，请先添加！");
			}

			if (Boolean.TRUE != supplier.getEnabled()) {
				throw new BusinessException("该供应商还未启用，请先启用！");
			}
		}

		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);

		FinanceAuditEntity audit1 = financeAuditService.inquireLatestFinanceAudit(financeAudit.getFinanceId());
		if (audit1 != null) {
			if (audit1.getBusinessSubmitState() == Boolean.TRUE) {
				throw new BusinessException("审核意见已提交，不能再次修改！");
			}
			audit1.setFinanceAmount(new BigDecimal(financeAudit.getFinanceAmount()));
			audit1.setBusinessAudit(financeAudit.getBusinessAudit());
			audit1.setBusinessAuditState(financeAudit.getBusinessAuditState());
			audit1.setBusinessAuditDate(DateUtil.formatDatetime(new Date()));
			audit1.setBusinessAuditorId(FinanceSessionContext.getAccountId());
			audit1.setBusinessAuditor(FinanceSessionContext.getAccountFullName());
			audit1.setFinanceAmount(new BigDecimal(financeAudit.getFinanceAmount()));
			financeAuditService.updateFinanceAuditEntity(audit1);
		} else {
			audit1 = FinanceApplicationCastor.fromFinanceAudit(financeAudit, audit1);
			audit1.setFinanceAmount(new BigDecimal(financeAudit.getFinanceAmount()));
			audit1.setFinanceId(financeEntity.getFinanceId());
			audit1.setFinanceNumber(financeEntity.getFinanceNumber());
			audit1.setFinanceAuditState(FinanceAuditEnum.PROCESSING);
			audit1.setCallback(Boolean.FALSE);
			audit1.setBusinessAudit(financeAudit.getBusinessAudit());
			audit1.setBusinessAuditState(financeAudit.getBusinessAuditState());
			audit1.setBusinessAuditDate(DateUtil.formatDatetime(new Date()));
			audit1.setBusinessAuditorId(FinanceSessionContext.getAccountId());
			audit1.setBusinessAuditor(FinanceSessionContext.getAccountFullName());
			audit1.setFinalState(ApiFinanceStateEnum.YW.getCode());
		}

		FiananceAuditInfo fai = new FiananceAuditInfo();
		fai.setAuditDate(DateUtil.formatDatetime(new Date()));
		fai.setAuditor(FinanceSessionContext.getAccountFullName());
		fai.setFinanceAuditId(audit1.getFinanceAuditId());

		if (Boolean.FALSE == financeAudit.getBusinessAuditState()) {
			financeAuditService.updateFinanceAuditEntity(audit1);
			return fai;
		}

		financeEntity.setLoanTimeLimit(financeAudit.getFinanceDays());
		financeEntity.setDistrainTimeLimit(financeAudit.getDistrain());
		financeEntity.setSettlementMethod(financeAudit.getSettlementMethod());
		if (StringUtil.isNotBlank(financeAudit.getBail())) {
			financeEntity.setBail(new BigDecimal(financeAudit.getBail()));
		}
		if(!StringUtils.isBlank(financeAudit.getFinanceAmount()))
			financeEntity.setFinanceAmount(new BigDecimal(financeAudit.getFinanceAmount()));
		if(!StringUtils.isBlank(financeAudit.getAuditInterest()))
			financeEntity.setAuditInterest(new BigDecimal(financeAudit.getAuditInterest()));
		financeApplicationService.renovateFinanceApplication(financeEntity);

		// 保存货物最低价、最高价
		BigDecimal evaluateAmount = BigDecimal.ZERO;
		List<FinanceBulkstockEntity> bulkstocks = new ArrayList<>();
		if(financeAudit.getBulkstockIds()!=null){
			for (int i = 0; i < financeAudit.getBulkstockIds().length; i++) {
				Long bulkstockId = financeAudit.getBulkstockIds()[i];
				FinanceBulkstockEntity bulkstock = financeBulkstockService.inquireFinanceBulkstock(bulkstockId);
				if(bulkstock!=null){
					bulkstock.setEvaluatePrice(CollectionUtils.getArrayIndexValue(financeAudit.getEvaluatePrice(), i));
					bulkstock.setHighestPrice(CollectionUtils.getArrayIndexValue(financeAudit.getHighestPrice(), i));
					bulkstock.setLowestPrice(CollectionUtils.getArrayIndexValue(financeAudit.getLowestPrice(), i));
					bulkstock.setFinalPrice(CollectionUtils.getArrayIndexValue(financeAudit.getFinalPrice(), i));
					evaluateAmount = evaluateAmount.add(bulkstock.getEvaluatePrice().multiply(bulkstock.getValuationQuantity()));
					bulkstocks.add(bulkstock);
				}
			}
		}

		if (StringUtil.isNotBlank(financeAudit.getMaterials())) {
			createFinanceMaterial(financeAudit.getMaterials(), financeAudit.getFinanceId(), audit1.getFinanceAuditId(), FinanceSegmentEnum.AUDIT_DATA);
		}

		//保存融资附件信息
		if (financeAudit.getFilesInfoId() != null) {
			for (int i = 0; i < financeAudit.getFilesInfoId().length; i++) {
				FinanceFilesInfoEntity ffie = new FinanceFilesInfoEntity();
				ffie.setFilesUuid(financeAudit.getFilesUuid()[i]);
				ffie.setFinanceId(financeEntity.getFinanceId());
				ffie.setNormFileName(financeAudit.getNormFileName()[i]);
				ffie.setNormId(financeAudit.getNormId()[i]);
				ffie.setFilesInfoId(financeAudit.getFilesInfoId()[i]);
				ffie.setIsNotNull(financeAudit.getIsNotNull()[i]);
				if (financeAudit.getFilesInfoId()[i] == null || financeAudit.getFilesInfoId()[i] == 0) {
					financeFilesInfoService.createFinanceFilesInfo(ffie);
				} else {
					financeFilesInfoService.updateFinanceFilesInfo(ffie);
				}
			}
		}

		for (FinanceBulkstockEntity bulkstock : bulkstocks) {
			financeBulkstockService.renovateFinanceBulkstock(bulkstock);
		}

		for (FinanceBulkstockEntity bulkstock : bulkstocks) {
			if (evaluateAmount.compareTo(BigDecimal.ZERO) <= 0) {
				evaluateAmount = new BigDecimal(1);
			}
			bulkstock.setFinancePrice(bulkstock.getEvaluatePrice().multiply(new BigDecimal(financeAudit.getFinanceAmount())).divide(evaluateAmount, 2, RoundingMode.HALF_UP)); // 融资单价=估值单价/全部货物估值总额*融资金额
			// (保留两位小数)
			financeBulkstockService.renovateFinanceBulkstock(bulkstock); 

			List<ContainerBulkstockEntity> cbes = containerBulkstockService.inquireContainerBulkstockListByBulkstockId(bulkstock.getBulkstockId());
			for (ContainerBulkstockEntity cbe : cbes) {
				cbe.setFinancePrice(bulkstock.getFinancePrice());
				containerBulkstockService.updateContainerBulkstock(cbe);
			}
		}

		if(financeAudit.getBulkstockIds()!=null && financeAudit.getBulkstockIds().length>0){
			for(int i=0; i<financeAudit.getBulkstockIds().length; i++) {
				EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(financeEntity.getEnterpriseId());
				FinanceBulkstockEntity fbe = financeBulkstockService.inquireFinanceBulkstock(financeAudit.getBulkstockIds()[i]);
				logger.info("grade.getGradeEvaluationId():" + grade.getGradeEvaluationId());
				logger.info("fbe.getBulkstockInfoId():" + fbe.getBulkstockInfoId());
				logger.info("ProductTypeEnum.valueOf(financeAudit.getProductType()):" + financeAudit.getProductType());
				FinanceBulkstockPledgeRateEntity fbpre = financeBulkstockPledgeRateService.inquireFinanceBulkstockPledgeRate(grade.getGradeEvaluationId(), fbe.getBulkstockInfoId(), ProductTypeEnum.valueOf(financeAudit.getProductType()));
				if (fbpre == null) {
					throw new BusinessException("该用户不能做该货品融资!");
				}
				if ((fbe.getFinancePrice().divide(fbe.getEvaluatePrice(), 2, BigDecimal.ROUND_HALF_DOWN).compareTo(fbpre.getPledgeRateCeiling()) > 0) && financeEntity.getProductType() != ProductTypeEnum.PURCHASING_STORAGE && financeEntity.getProductType() != ProductTypeEnum.PURCHASING) {
					throw new BusinessException("许可质押率大于所设定的质押率!");
				}
				if (financeAudit.getIntrerst().compareTo(fbpre.getLoanRateCeiling()) < 0) {
					throw new BusinessException("许可利率小于所设定的利率!");
				}
			}
		}

		if (FinanceStateEnum.APPROVE != financeEntity.getFinanceState() && FinanceStateEnum.WAIT_APPROVE != financeEntity.getFinanceState()) {
			throw new BusinessException("不可操作,只能对处于审批状态中的融资申请进行操作");
		}

		if (StringUtil.isNotBlank(financeAudit.getBail())) {
			audit1.setBail(new BigDecimal(financeAudit.getBail()));
		}
		audit1.setFinalState(ApiFinanceStateEnum.YW.getCode());
		audit1.setBusinessManageAuditState(Boolean.TRUE);
		audit1.setOperationAuditState(Boolean.TRUE);
		audit1.setOperationManageAuditState(Boolean.TRUE);
		audit1.setRiskAuditState(Boolean.TRUE);
		audit1.setRiskMemberAuditState(Boolean.TRUE);
		audit1.setCallback(Boolean.FALSE);
		audit1.setFinanceNumber(financeEntity.getFinanceNumber());
		//		audit1.setFinanceAuditState(FinanceAuditEnum.COMPLETED);
		financeAuditService.updateFinanceAuditEntity(audit1);

		if (StringUtil.isNotBlank(financeAudit.getMaterials())) {
			createFinanceMaterial(financeAudit.getMaterials(), financeAudit.getFinanceId(), audit1.getFinanceAuditId(), FinanceSegmentEnum.AUDIT_DATA);
		}

		//生成产品信息
		FinanceProductInnerEntity productInner = financeProductInnerService.inquireFinanceProductInner(financeAudit.getFinanceId(), null);
		if (productInner == null) {
			productInner = new FinanceProductInnerEntity();
		}
		productInner.setProductType(ProductTypeEnum.valueOf(financeAudit.getProductType()));
		productInner.setInterest(financeAudit.getIntrerst());
		productInner.setFinanceDays(financeAudit.getFinanceDays());
		productInner.setCycle(financeAudit.getCycle());
		productInner.setFinanceId(financeEntity.getFinanceId());
		productInner.setEnterpriseId(financeEntity.getFinanceId());
		productInner.setEnterpriseName(financeEntity.getEnterpriseName());
		productInner.setBailRate(financeAudit.getBailRate());
		productInner.setDistrain(financeAudit.getDistrain());
		financeProductInnerService.createFinanceProductInner(productInner);

		//若不为运费保理，保存计息项
		if (ProductTypeEnum.FREIGHT_FACTORING != financeEntity.getProductType()) {
			List<FinanceProductInterestItemEntity> fpiies = financeProductInterestItemService.inquireFinanceProductInterestItemList(productInner.getFinanceProductId());
			for (FinanceProductInterestItemEntity fppie : fpiies) {
				financeProductInterestItemService.deleteFinanceProductInterestItem(fppie.getFinanceProductInterestItemId());
			}

			if(financeAudit.getFinanceProductInterestItemName()!=null){
				for (int i=0; i<financeAudit.getFinanceProductInterestItemName().length; i++) {
					FinanceProductInterestItemEntity interestItem = financeProductInterestItemService.inquireFinanceProductInterestItem(financeAudit.getFinanceProductInterestItemId()[i]);
					if (interestItem != null) {
						financeProductInterestItemService.deleteFinanceProductInterestItem(interestItem.getFinanceProductInterestItemId());
					}
					interestItem = new FinanceProductInterestItemEntity();
					interestItem.setFinanceProductInterestItemName(financeAudit.getFinanceProductInterestItemName()[i]);
					interestItem.setFinanceProductId(productInner.getFinanceProductId());
					interestItem.setStartDay(financeAudit.getStartDay()[i]);
					interestItem.setEndDay(financeAudit.getEndDay()[i]);
					interestItem.setAmout(financeAudit.getInterestRate()[i]);
					interestItem.setBillingMethod(BillingMethodEnum.valueOf(financeAudit.getBillingType()[i]));
					financeProductInterestItemService.createFinanceProductInterestItem(interestItem);
				}
			}
		}

		return fai;
	}

	@Override
	@Transactional
	public FiananceAuditInfo supplementBussinessManageAuditOpinion(FinanceAudit financeAudit) {
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeAudit.getFinanceId());
		FiananceAuditInfo fai = new FiananceAuditInfo();
		fai.setAuditDate(DateUtil.formatDatetime(new Date()));
		fai.setAuditor(FinanceSessionContext.getAccountFullName());
		if (FinanceStateEnum.APPROVE != financeEntity.getFinanceState() && FinanceStateEnum.WAIT_APPROVE != financeEntity.getFinanceState()) {
			throw new BusinessException("不可操作,只能对处于审批状态中的融资申请进行操作");
		}
		FinanceAuditEntity audit1 = financeAuditService.inquireLatestFinanceAudit(financeAudit.getFinanceId());

		if (audit1.getBusinessManageSubmitState() == Boolean.TRUE) {
			throw new BusinessException("审核意见已提交，不能再次修改！");
		}

		audit1.setBusinessManageAudit(financeAudit.getBusinessManageAudit());
		audit1.setBusinessManageAuditState(financeAudit.getBusinessManageAuditState());
		audit1.setBusinessManageAuditDate(DateUtil.formatDatetime(new Date()));
		audit1.setBusinessManageAuditorId(FinanceSessionContext.getAccountId());
		audit1.setBusinessManageAuditor(FinanceSessionContext.getAccountFullName());
		financeAuditService.updateFinanceAuditEntity(audit1);

		fai.setFinanceAuditId(audit1.getFinanceAuditId());
		return fai;
	}

	@Override
	@Transactional
	public FiananceAuditInfo supplementOperationAuditOpinion(FinanceAudit financeAudit) {
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeAudit.getFinanceId());
		FiananceAuditInfo fai = new FiananceAuditInfo();

		String[] statementSource = new String[] { "FINANCE_AUDIT", "BAIL_ADDITION" };
		FinanceMoneyStatementEntity statement = financeMoneyStatementService.inquireFinanceMoneyStatementDetail(statementSource, financeEntity.getFinanceId());
		if (statement != null && !statement.getReceiptVerifiState()) {
			throw new BusinessException("保证金未核销,不允许操作");
		}

		fai.setAuditDate(DateUtil.formatDatetime(new Date()));
		fai.setAuditor(FinanceSessionContext.getAccountFullName());
		if (FinanceStateEnum.APPROVE != financeEntity.getFinanceState() && FinanceStateEnum.WAIT_APPROVE != financeEntity.getFinanceState()) {
			throw new BusinessException("不可操作,只能对处于审批状态中的融资申请进行操作");
		}

		FinanceAuditEntity audit1 = financeAuditService.inquireLatestFinanceAudit(financeAudit.getFinanceId());

		if (audit1.getOperationSubmitState() == Boolean.TRUE) {
			throw new BusinessException("审核意见已提交，不能再次修改！");
		}
		audit1.setOperationAudit(financeAudit.getOperationAudit());
		audit1.setOperationAuditState(financeAudit.getOperationAuditState());
		audit1.setOperationAuditDate(DateUtil.formatDatetime(new Date()));
		audit1.setOperationAuditorId(FinanceSessionContext.getAccountId());
		audit1.setOperationAuditor(FinanceSessionContext.getAccountFullName());
		financeAuditService.updateFinanceAuditEntity(audit1);

		fai.setFinanceAuditId(audit1.getFinanceAuditId());
		return fai;
	}

	@Override
	@Transactional
	public FiananceAuditInfo supplementOperationManageAuditOpinion(FinanceAudit financeAudit) {
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeAudit.getFinanceId());
		FiananceAuditInfo fai = new FiananceAuditInfo();
		fai.setAuditDate(DateUtil.formatDatetime(new Date()));
		fai.setAuditor(FinanceSessionContext.getAccountFullName());

		FinanceAuditEntity audit1 = financeAuditService.inquireLatestFinanceAudit(financeAudit.getFinanceId());

		if (FinanceStateEnum.APPROVE != financeEntity.getFinanceState() && FinanceStateEnum.WAIT_APPROVE != financeEntity.getFinanceState()) {
			throw new BusinessException("不可操作,只能对处于审批状态中的融资申请进行操作");
		}

		if (audit1.getOperationManageSubmitState() == Boolean.TRUE) {
			throw new BusinessException("审核意见已提交，不能再次修改！");
		}
		audit1.setOperationManageAudit(financeAudit.getOperationManageAudit());
		audit1.setOperationManageAuditState(financeAudit.getOperationManageAuditState());
		audit1.setOperationManageAuditDate(DateUtil.formatDatetime(new Date()));
		audit1.setOperationManageAuditorId(FinanceSessionContext.getAccountId());
		audit1.setOperationManageAuditor(FinanceSessionContext.getAccountFullName());
		financeAuditService.updateFinanceAuditEntity(audit1);

		fai.setFinanceAuditId(audit1.getFinanceAuditId());
		return fai;
	}

	@Override
	@Transactional
	public FiananceAuditInfo supplementRiskAuditOpinion(FinanceAudit financeAudit) {
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeAudit.getFinanceId());
		FiananceAuditInfo fai = new FiananceAuditInfo();
		fai.setAuditDate(DateUtil.formatDatetime(new Date()));
		fai.setAuditor(FinanceSessionContext.getAccountFullName());

		FinanceAuditEntity audit1 = financeAuditService.inquireLatestFinanceAudit(financeAudit.getFinanceId());

		if (FinanceStateEnum.APPROVE != financeEntity.getFinanceState() && FinanceStateEnum.WAIT_APPROVE != financeEntity.getFinanceState()) {
			throw new BusinessException("不可操作,只能对处于审批状态中的融资申请进行操作");
		}

		audit1 = financeAuditService.inquireFinanceAudit(financeAudit.getFinanceAuditId());
		if (audit1.getRiskSubmitState() == Boolean.TRUE) {
			throw new BusinessException("审核意见已提交，不能再次修改！");
		}
		audit1.setRiskAudit(financeAudit.getRiskAudit());
		audit1.setRiskAuditState(financeAudit.getRiskAuditState());
		audit1.setRiskAuditDate(DateUtil.formatDatetime(new Date()));
		audit1.setRiskAuditorId(FinanceSessionContext.getAccountId());
		audit1.setRiskAuditor(FinanceSessionContext.getAccountFullName());
		financeAuditService.updateFinanceAuditEntity(audit1);

		fai.setFinanceAuditId(audit1.getFinanceAuditId());

		//		if (StringUtil.isBlank(FinanceSessionContext.getIsApp())) {
//		if (true) {
//			financeEntity.setLoanTimeLimit(financeAudit.getFinanceDays());
//			financeEntity.setDistrainTimeLimit(financeAudit.getDistrain());
//			if(financeAudit.getBailRate() != null && StringUtil.isNotBlank(financeAudit.getFinanceAmount())) {
//				financeEntity.setBail((financeAudit.getBailRate().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP)).multiply(new BigDecimal(financeAudit.getFinanceAmount())).setScale(2, BigDecimal.ROUND_HALF_UP));
//			}
//			if(!StringUtils.isBlank(financeAudit.getFinanceAmount())) {
//				financeEntity.setFinanceAmount(new BigDecimal(financeAudit.getFinanceAmount()));
//				audit1.setFinanceAmount(new BigDecimal(financeAudit.getFinanceAmount()));
//			}
//			if(!StringUtils.isBlank(financeAudit.getAuditInterest()))
//				financeEntity.setAuditInterest(new BigDecimal(financeAudit.getAuditInterest()));
//			financeApplicationService.renovateFinanceApplication(financeEntity);
//
//			// 保存货物最低价、最高价
//			BigDecimal evaluateAmount = BigDecimal.ZERO;
//			List<FinanceBulkstockEntity> bulkstocks = new ArrayList<>();
//			if(financeAudit.getBulkstockIds()!=null){
//				for (int i = 0; i < financeAudit.getBulkstockIds().length; i++) {
//					Long bulkstockId = financeAudit.getBulkstockIds()[i];
//					FinanceBulkstockEntity bulkstock = financeBulkstockService.inquireFinanceBulkstock(bulkstockId);
//					if(bulkstock!=null){
//						bulkstock.setEvaluatePrice(CollectionUtils.getArrayIndexValue(financeAudit.getEvaluatePrice(), i));
//						bulkstock.setHighestPrice(CollectionUtils.getArrayIndexValue(financeAudit.getHighestPrice(), i));
//						bulkstock.setLowestPrice(CollectionUtils.getArrayIndexValue(financeAudit.getLowestPrice(), i));
//						evaluateAmount = evaluateAmount.add(bulkstock.getEvaluatePrice().multiply(bulkstock.getValuationQuantity()));
//						bulkstocks.add(bulkstock);
//					}
//				}
//			}
//
//			//保存融资附件信息
//			if (financeAudit.getFilesInfoId() != null) {
//				for (int i = 0; i < financeAudit.getFilesInfoId().length; i++) {
//					FinanceFilesInfoEntity ffie = new FinanceFilesInfoEntity();
//					ffie.setFilesUuid(financeAudit.getFilesUuid()[i]);
//					ffie.setFinanceId(financeEntity.getFinanceId());
//					ffie.setNormFileName(financeAudit.getNormFileName()[i]);
//					ffie.setNormId(financeAudit.getNormId()[i]);
//					ffie.setFilesInfoId(financeAudit.getFilesInfoId()[i]);
//					ffie.setIsNotNull(financeAudit.getIsNotNull()[i]);
//					if (financeAudit.getFilesInfoId()[i] == null || financeAudit.getFilesInfoId()[i] == 0) {
//						financeFilesInfoService.createFinanceFilesInfo(ffie);
//					} else {
//						financeFilesInfoService.updateFinanceFilesInfo(ffie);
//					}
//				}
//			}
//
//			for (FinanceBulkstockEntity bulkstock : bulkstocks) {
//				financeBulkstockService.renovateFinanceBulkstock(bulkstock);
//			}
//
//			for (FinanceBulkstockEntity bulkstock : bulkstocks) {
//				bulkstock.setFinancePrice(bulkstock.getEvaluatePrice().multiply(new BigDecimal(financeAudit.getFinanceAmount())).divide(evaluateAmount, 2, RoundingMode.HALF_UP)); // 融资单价=估值单价/全部货物估值总额*融资金额
//				// (保留两位小数)
//				financeBulkstockService.renovateFinanceBulkstock(bulkstock); 
//
//				List<ContainerBulkstockEntity> cbes = containerBulkstockService.inquireContainerBulkstockListByBulkstockId(bulkstock.getBulkstockId());
//				for (ContainerBulkstockEntity cbe : cbes) {
//					cbe.setFinancePrice(bulkstock.getFinancePrice());
//					containerBulkstockService.updateContainerBulkstock(cbe);
//				}
//			}
//
//			if(financeAudit.getBulkstockIds()!=null && financeAudit.getBulkstockIds().length>0){
//				for(int i=0; i<financeAudit.getBulkstockIds().length; i++) {
//					EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(financeEntity.getEnterpriseId());
//					FinanceBulkstockEntity fbe = financeBulkstockService.inquireFinanceBulkstock(financeAudit.getBulkstockIds()[i]);
//					FinanceBulkstockPledgeRateEntity fbpre = financeBulkstockPledgeRateService.inquireFinanceBulkstockPledgeRate(grade.getGradeEvaluationId(), fbe.getBulkstockInfoId(), ProductTypeEnum.valueOf(financeAudit.getProductType()));
//					if (fbpre == null) {
//						throw new BusinessException("该用户不能做该货品融资!");
//					}
//					if ((fbe.getFinancePrice().divide(fbe.getEvaluatePrice(), 2, BigDecimal.ROUND_HALF_DOWN).compareTo(fbpre.getPledgeRateCeiling()) > 0) && financeEntity.getProductType() != ProductTypeEnum.PURCHASING_STORAGE && financeEntity.getProductType() != ProductTypeEnum.PURCHASING) {
//						throw new BusinessException("许可质押率大于所设定的质押率!");
//					}
//					if (financeAudit.getIntrerst().compareTo(fbpre.getLoanRateCeiling()) < 0) {
//						throw new BusinessException("许可利率小于所设定的利率!");
//					}
//				}
//			}
//
//			if (FinanceStateEnum.APPROVE != financeEntity.getFinanceState() && FinanceStateEnum.WAIT_APPROVE != financeEntity.getFinanceState()) {
//				throw new BusinessException("不可操作,只能对处于审批状态中的融资申请进行操作");
//			}
//
//			if (financeAudit.getBailRate() != null && StringUtil.isNotBlank(financeAudit.getFinanceAmount())) {
//				audit1.setBail((financeAudit.getBailRate().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP)).multiply(new BigDecimal(financeAudit.getFinanceAmount())).setScale(2, BigDecimal.ROUND_HALF_UP));
//			}
//			audit1.setBusinessManageAuditState(Boolean.TRUE);
//			audit1.setOperationAuditState(Boolean.TRUE);
//			audit1.setOperationManageAuditState(Boolean.TRUE);
//			audit1.setRiskAuditState(Boolean.TRUE);
//			audit1.setRiskMemberAuditState(Boolean.TRUE);
//			audit1.setCallback(Boolean.FALSE);
//			audit1.setFinanceNumber(financeEntity.getFinanceNumber());
//			//		audit1.setFinanceAuditState(FinanceAuditEnum.COMPLETED);
//			financeAuditService.updateFinanceAuditEntity(audit1);
//
//			if (StringUtil.isNotBlank(financeAudit.getMaterials())) {
//				createFinanceMaterial(financeAudit.getMaterials(), financeAudit.getFinanceId(), audit1.getFinanceAuditId(), FinanceSegmentEnum.AUDIT_DATA);
//			}
//
//			//生成产品信息
//			FinanceProductInnerEntity productInner = financeProductInnerService.inquireFinanceProductInner(financeAudit.getFinanceId(), null);
//			if (productInner == null) {
//				productInner = new FinanceProductInnerEntity();
//			}
//			productInner.setProductType(ProductTypeEnum.valueOf(financeAudit.getProductType()));
//			productInner.setInterest(financeAudit.getIntrerst());
//			productInner.setFinanceDays(financeAudit.getFinanceDays());
//			productInner.setCycle(financeAudit.getCycle());
//			productInner.setFinanceId(financeEntity.getFinanceId());
//			productInner.setEnterpriseId(financeEntity.getFinanceId());
//			productInner.setEnterpriseName(financeEntity.getEnterpriseName());
//			productInner.setBailRate(financeAudit.getBailRate());
//			productInner.setDistrain(financeAudit.getDistrain());
//			financeProductInnerService.createFinanceProductInner(productInner);
//
//			//若不为运费保理，保存计息项
//			if (ProductTypeEnum.FREIGHT_FACTORING != financeEntity.getProductType()) {
//				List<FinanceProductInterestItemEntity> fpiies = financeProductInterestItemService.inquireFinanceProductInterestItemList(productInner.getFinanceProductId());
//				for (FinanceProductInterestItemEntity fppie : fpiies) {
//					financeProductInterestItemService.deleteFinanceProductInterestItem(fppie.getFinanceProductInterestItemId());
//				}
//
//				if(financeAudit.getFinanceProductInterestItemName()!=null){
//					for (int i=0; i<financeAudit.getFinanceProductInterestItemName().length; i++) {
//						FinanceProductInterestItemEntity interestItem = financeProductInterestItemService.inquireFinanceProductInterestItem(financeAudit.getFinanceProductInterestItemId()[i]);
//						if (interestItem != null) {
//							financeProductInterestItemService.deleteFinanceProductInterestItem(interestItem.getFinanceProductInterestItemId());
//						}
//						interestItem = new FinanceProductInterestItemEntity();
//						interestItem.setFinanceProductInterestItemName(financeAudit.getFinanceProductInterestItemName()[i]);
//						interestItem.setFinanceProductId(productInner.getFinanceProductId());
//						interestItem.setStartDay(financeAudit.getStartDay()[i]);
//						interestItem.setEndDay(financeAudit.getEndDay()[i]);
//						interestItem.setAmout(financeAudit.getInterestRate()[i]);
//						interestItem.setBillingMethod(BillingMethodEnum.valueOf(financeAudit.getBillingType()[i]));
//						financeProductInterestItemService.createFinanceProductInterestItem(interestItem);
//					}
//				}
//			}
//
//		}

		return fai;
	}

	@Override
	@Transactional
	public FiananceAuditInfo supplementRiskMemberAuditOpinion(FinanceAudit financeAudit) {
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeAudit.getFinanceId());
		FiananceAuditInfo fai = new FiananceAuditInfo();
		fai.setAuditDate(DateUtil.formatDatetime(new Date()));
		fai.setAuditor(FinanceSessionContext.getAccountFullName());

		if (FinanceStateEnum.APPROVE != financeEntity.getFinanceState() && FinanceStateEnum.WAIT_APPROVE != financeEntity.getFinanceState()) {
			throw new BusinessException("不可操作,只能对处于审批状态中的融资申请进行操作");
		}
		FinanceAuditEntity audit1 = financeAuditService.inquireLatestFinanceAudit(financeAudit.getFinanceId());

		if (audit1.getRiskMemberSubmitState() == Boolean.TRUE) {
			throw new BusinessException("审核意见已提交，不能再次修改！");
		}
		audit1.setRiskMemberAudit(financeAudit.getRiskMemberAudit());
		audit1.setRiskMemberAuditState(financeAudit.getRiskMemberAuditState());
		audit1.setRiskMemberAuditDate(DateUtil.formatDatetime(new Date()));
		audit1.setRiskMemberAuditorId(FinanceSessionContext.getAccountId());
		audit1.setRiskMemberAuditor(FinanceSessionContext.getAccountFullName());
		financeAuditService.updateFinanceAuditEntity(audit1);

		fai.setFinanceAuditId(audit1.getFinanceAuditId());
		return fai;
	}

	@Override
	@Transactional
	public void submitBussinessAuditOpinion(FinanceAudit financeAudit) {
		if (StringUtil.isBlank(financeAudit.getDeviceType())) {
			supplementBussinessAuditOpinion(financeAudit);
		}
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		FinanceAuditEntity entity = financeAuditService.inquireLatestFinanceAudit(financeAudit.getFinanceId());
		if (entity != null && entity.getBusinessSubmitState() != null && entity.getBusinessSubmitState() == Boolean.TRUE) {
			throw new BusinessException("审核意见已提交，不能再次修改！");
		}

		FinanceAuditLogEntity fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), financeAudit.getBusinessAuditState() ? 1L:0, "商务部:"+financeAudit.getBusinessAudit(), entity.getFinanceId(), 1L, FinanceSessionContext.getAccountId());
		financeAuditLogService.createFinanceAuditLogEntity(fale);
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(entity.getFinanceId());
		
		EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(finance.getEnterpriseId());
		
		logger.info("------业务提交：网页状态"+financeAudit.getBusinessAuditState()+"后台查询状态"+entity.getBusinessAuditState());
		if (Boolean.TRUE == financeAudit.getBusinessAuditState()) {
			if (DateUtils.daysBetween(DateUtils.now(), DateUtils.fromDateInt(grade.getEffectiveEndDate())) - finance.getLoanTimeLimit() < 0) {
				throw new BusinessException("该企业授信有效截止时间为："+DateUtil.formatDate(DateUtils.fromDateInt(grade.getEffectiveEndDate()))+"，已超过了合理期限，提交失败。");
			}
			entity.setBusinessSubmitState(Boolean.TRUE);
			financeAuditService.updateFinanceAuditEntity(entity);
			if (ProductTypeEnum.PURCHASING_STORAGE == finance.getProductType() || ProductTypeEnum.PROXY_SALE == finance.getProductType()) {
				entity.setFinalState(ApiFinanceStateEnum.SWMANAGE.getCode());
				//消息推送
				SendLetterMessage.sendLetterMessage("businessManageAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "商务部领导审核"));
			} else {
				entity.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
				List<FinanceBulkstockEntity> fbes = financeBulkstockService.inquireFinanceBulkstockList(finance.getFinanceId());
				FinanceCompleteResultEntity fcre = new FinanceCompleteResultEntity(finance.getFinanceId(), fbes.get(0).getBulkstockName(), fbes.get(0).getQuantity(), fbes.get(0).getUnit(), ApiTypeEnum.RZ.getCode(), finance.getFinanceId(), entity.getFinanceAuditId(), entity.getAuditNumber(), Long.valueOf(FinanceAuditEnum.FIRSTCOMPLETE.ordinal()), DateUtil.now(), finance.getEnterpriseName(), finance.getProductName(), finance.getApplicationAmount());
				financeAuditLogService.createFinanceCompleteResultEntity(fcre);
				if (Boolean.TRUE == finance.getCallback()) {
					if (ProductTypeEnum.MANIFEST_PLEDGE == finance.getProductType() || ProductTypeEnum.PROXY_SALE == finance.getProductType() || ProductTypeEnum.PURCHASING_STORAGE == finance.getProductType()) {
						finance.setFinanceState(FinanceStateEnum.FIRSTCOMPLETE);
						//消息推送-通知锁定noticeReceive_1
						SendLetterMessage.sendLetterMessage("noticeReceive_1", String.format(tmp1, finance.getEnterpriseName(), finance.getFinanceNumber(), "通知锁定"));
					} else {
						finance.setFinanceState(FinanceStateEnum.WAIT_PROTOCOL);
					}
				} else {
					finance.setFinanceState(FinanceStateEnum.FIRSTCOMPLETE);
					//消息推送-通知锁定noticeReceive_1
					SendLetterMessage.sendLetterMessage("noticeReceive_1", String.format(tmp1, finance.getEnterpriseName(), finance.getFinanceNumber(), "通知锁定"));
				}
			}
			
			finance.setCallback(Boolean.FALSE);
			financeApplicationService.updateFinanceApplication(finance);
		} else {
			entity.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
			entity.setBusinessSubmitState(Boolean.FALSE);
			initFinanceApplication(entity);
			rejectFinanceApplication(entity.getFinanceId(), null);
			FinanceLetterBlockingQueue.putEnterpriseExceptionLetter(finance.getEnterpriseId(), "审批结果", "尊敬的客户：%s，您所发起的融资申请已被决绝，请重新填写后再次提交，客服热线:021-6094 5016", finance.getEnterpriseName());
			//删除审批表记录
			financeAuditService.deleteFinanceAuditEntity(entity);
		}
	}

	@Override
	@Transactional
	public void submitBussinessManageAuditOpinion(FinanceAudit financeAudit) {
		if (StringUtil.isBlank(financeAudit.getDeviceType())) {
			supplementBussinessManageAuditOpinion(financeAudit);
		}
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		FinanceAuditEntity entity = financeAuditService.inquireLatestFinanceAudit(financeAudit.getFinanceId());
		if (entity.getBusinessManageSubmitState() == Boolean.TRUE) {
			throw new BusinessException("审核意见已提交，不能再次修改！");
		}
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(entity.getFinanceId());
		FinanceAuditLogEntity fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), entity.getBusinessManageAuditState() ? 1L:0, "商务领导" + entity.getBusinessManageAudit(), entity.getFinanceId(), 1L,FinanceSessionContext.getAccountId());
		
		EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(finance.getEnterpriseId());

		if (DateUtils.daysBetween(DateUtils.now(), DateUtils.fromDateInt(grade.getEffectiveEndDate())) - finance.getLoanTimeLimit() < 0) {
			throw new BusinessException("该企业授信有效截止时间为："+DateUtil.formatDate(DateUtils.fromDateInt(grade.getEffectiveEndDate()))+"，已超过了合理期限，提交失败。");
		}
		
		financeAuditLogService.createFinanceAuditLogEntity(fale);
		if (Boolean.FALSE == financeAudit.getBusinessManageAuditState()) {
			initFinanceApplication(entity);

			//消息推送-业务审核businessAudit_1
			SendLetterMessage.sendLetterMessage("businessAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "商务审核"));
		} else {
			entity.setBusinessManageSubmitState(Boolean.TRUE);
			if (ProductTypeEnum.PURCHASING_STORAGE == finance.getProductType()) {
				entity.setFinalState(ApiFinanceStateEnum.ZJ.getCode());
				//消息推送-财务确认
				SendLetterMessage.sendLetterMessage("operationAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "财务确认"));
				// 代采 保证金生成 客户->平台 付款单
				if (finance.getBail() != null && finance.getBail().compareTo(BigDecimal.ZERO) > 0) {
					FinanceMoneyStatementEntity moneyEntity = FinanceLoanCastor.fromFinanceAuditBail(finance, entity);
					financeMoneyStatementService.createFinanceMoneyStatement(moneyEntity);
				}
			} else {
				entity.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
				entity.setFinanceAuditState(FinanceAuditEnum.FIRSTCOMPLETE);
				finance.setFinanceState(FinanceStateEnum.FIRSTCOMPLETE);

				financeApplicationService.updateFinanceApplication(finance);
				List<FinanceBulkstockEntity> fbes = financeBulkstockService.inquireFinanceBulkstockList(finance.getFinanceId());
				FinanceCompleteResultEntity fcre = new FinanceCompleteResultEntity(finance.getFinanceId(), fbes.get(0).getBulkstockName(), fbes.get(0).getQuantity(), fbes.get(0).getUnit(), ApiTypeEnum.RZ.getCode(), finance.getFinanceId(), entity.getFinanceAuditId(), entity.getAuditNumber(), Long.valueOf(FinanceAuditEnum.FIRSTCOMPLETE.ordinal()), DateUtil.now(), finance.getEnterpriseName(), finance.getProductName(), finance.getApplicationAmount());
				financeAuditLogService.createFinanceCompleteResultEntity(fcre);

				initEnterpriseEnterprise(finance.getEnterpriseId());
				
				//消息推送-通知锁定noticeReceive_1
				SendLetterMessage.sendLetterMessage("noticeReceive_1", String.format(tmp1, finance.getEnterpriseName(), finance.getFinanceNumber(), "通知锁定"));

			}
		}
		financeAuditService.updateFinanceAuditEntity(entity);
	}

	@Override
	@Transactional
	public void submitOperationAuditOpinion(FinanceAudit financeAudit) {
		if (StringUtil.isBlank(financeAudit.getDeviceType())) {
			supplementOperationAuditOpinion(financeAudit);
		}

		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		FinanceAuditEntity entity = financeAuditService.inquireLatestFinanceAudit(financeAudit.getFinanceId());

		if (entity.getOperationSubmitState() == Boolean.TRUE) {
			throw new BusinessException("审核意见已提交，不能再次修改！");
		}
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(entity.getFinanceId());
		FinanceAuditLogEntity fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), entity.getOperationAuditState() ? 1L:0, "财务确认:" + entity.getOperationAudit(), entity.getFinanceId(), 1L,FinanceSessionContext.getAccountId());
		
		EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(finance.getEnterpriseId());

		if (DateUtils.daysBetween(DateUtils.now(), DateUtils.fromDateInt(grade.getEffectiveEndDate())) - finance.getLoanTimeLimit() < 0) {
			throw new BusinessException("该企业授信有效截止时间为："+DateUtil.formatDate(DateUtils.fromDateInt(grade.getEffectiveEndDate()))+"，已超过了合理期限，提交失败。");
		}
		
		financeAuditLogService.createFinanceAuditLogEntity(fale);
		if (Boolean.FALSE == financeAudit.getOperationAuditState()) {
			initFinanceApplication(entity);

			//消息推送-业务审核
			SendLetterMessage.sendLetterMessage("businessAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "商务审核"));
		} else {

			entity.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
			entity.setOperationSubmitState(Boolean.TRUE);

			if (Boolean.TRUE == finance.getCallback()) {
				finance.setFinanceState(FinanceStateEnum.WAIT_PROTOCOL);
			} else {
				finance.setFinanceState(FinanceStateEnum.FIRSTCOMPLETE);
			}

			if ((ProductTypeEnum.PURCHASING == finance.getProductType() || ProductTypeEnum.PURCHASING_STORAGE == finance.getProductType()) && finance.getSettlementMethod() == 2) {
				finance.setFinanceState(FinanceStateEnum.WAIT_PROTOCOL);
			}

			financeApplicationService.updateFinanceApplication(finance);
			financeAuditService.updateFinanceAuditEntity(entity);

			List<FinanceBulkstockEntity> fbes = financeBulkstockService.inquireFinanceBulkstockList(finance.getFinanceId());
			FinanceCompleteResultEntity fcre = new FinanceCompleteResultEntity(finance.getFinanceId(), fbes.get(0).getBulkstockName(), fbes.get(0).getQuantity(), fbes.get(0).getUnit(), ApiTypeEnum.RZ.getCode(), finance.getFinanceId(), entity.getFinanceAuditId(), entity.getAuditNumber(), Long.valueOf(FinanceAuditEnum.FIRSTCOMPLETE.ordinal()), DateUtil.now(), finance.getEnterpriseName(), finance.getProductName(), finance.getApplicationAmount());
			financeAuditLogService.createFinanceCompleteResultEntity(fcre);
			
			initEnterpriseEnterprise(finance.getEnterpriseId());
		}
		financeAuditService.updateFinanceAuditEntity(entity);
	}

	@Override
	@Transactional
	public void submitOperationManageAuditOpinion(FinanceAudit financeAudit) {
		if (StringUtil.isBlank(financeAudit.getDeviceType())) {
			supplementOperationManageAuditOpinion(financeAudit);
		}
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		FinanceAuditEntity entity = financeAuditService.inquireLatestFinanceAudit(financeAudit.getFinanceId());
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(entity.getFinanceId());
		if (entity.getOperationManageSubmitState() == Boolean.TRUE) {
			throw new BusinessException("审核意见已提交，不能再次修改！");
		}
		
		EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(finance.getEnterpriseId());

		if (DateUtils.daysBetween(DateUtils.now(), DateUtils.fromDateInt(grade.getEffectiveEndDate())) - finance.getLoanTimeLimit() < 0) {
			throw new BusinessException("该企业授信有效截止时间为："+DateUtil.formatDate(DateUtils.fromDateInt(grade.getEffectiveEndDate()))+"，已超过了合理期限，提交失败。");
		}

		FinanceAuditLogEntity fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), entity.getOperationManageAuditState() ? 1L:0, "副总经理:" + entity.getOperationManageAudit(), entity.getFinanceId(), 1L,FinanceSessionContext.getAccountId());

		financeAuditLogService.createFinanceAuditLogEntity(fale);
		financeAuditService.updateFinanceAuditEntity(entity);
		if (Boolean.FALSE == financeAudit.getOperationManageAuditState()) {
			finance.setFinanceState(FinanceStateEnum.APPROVE);
			finance.setConstractState(ConstractStateEnum.UNSUBMIT);
			initFinanceApplication(entity);
			finance.setCallback(Boolean.TRUE);
			entity.setFinanceAuditState(FinanceAuditEnum.PROCESSING);
			SendLetterMessage.sendLetterMessage("businessAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "商务审核"));
		} else {
			entity.setFinanceNumber(finance.getFinanceNumber());
			entity.setFinanceAuditState(FinanceAuditEnum.COMPLETED);

			entity.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
			//			auditFinanceApplication(financeAudit, finance, entity);
			consentFinanceApplication(financeAudit);
			FinanceLetterBlockingQueue.putEnterpriseExceptionLetter(finance.getEnterpriseId(), "审批结果", "尊敬的客户：%s，您所发起的融资申请已通过，客服热线:021-6094 5016", finance.getEnterpriseName());

			//货箱补差
			List<ContainerInventoryEntity> inventories = containerInventoryService.inquireSupervisionFinanceAmountList(finance.getFinanceId());
			BigDecimal fa = BigDecimal.ZERO;
			for (ContainerInventoryEntity cie : inventories) {
				List<ContainerBulkstockEntity> cbes = containerBulkstockService.inquireContainerBulkstockList(cie.getInventoryId());
				for (ContainerBulkstockEntity cbe : cbes) {
					fa = fa.add(cbe.getValuationFinanceAmount());
				}
				fa = fa.add(cie.getAdjustment());
			}
			ContainerInventoryEntity last = inventories.get(inventories.size() - 1);
			last.setAdjustment(finance.getFinanceAmount().subtract(fa));
			containerInventoryService.updateContainerInventory(last);

			entity.setOperationManageSubmitState(Boolean.TRUE);

			List<FinanceCompleteResultEntity> fcres = financeAuditLogService.checkCompleteResultDate(finance.getFinanceId(), ApiTypeEnum.RZ.getCode());
			FinanceCompleteResultEntity fcre = fcres.get(0);
			if (fcre != null) {
				fcre.setFinalState(Long.valueOf(FinanceAuditEnum.COMPLETED.ordinal()));
				financeAuditLogService.updateFinanceCompleteResultEntity(fcre);
			}
		}

		financeApplicationService.updateFinanceApplication(finance);
		financeAuditService.updateFinanceAuditEntity(entity);
	}

	@Override
	@Transactional
	public void submitRiskAuditOpinion(FinanceAudit financeAudit) { 
		if (StringUtil.isBlank(financeAudit.getDeviceType())) {
			supplementRiskAuditOpinion(financeAudit);
		}
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		FinanceAuditEntity entity = financeAuditService.inquireFinanceAudit(financeAudit.getFinanceAuditId());
		if (entity.getRiskSubmitState() == Boolean.TRUE) {
			throw new BusinessException("审核意见已提交，不能再次修改！");
		}

		FinanceAuditLogEntity fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), financeAudit.getRiskAuditState() ? 1L:0, "风控部:" + entity.getRiskAudit(), entity.getFinanceId(), 1L,FinanceSessionContext.getAccountId());
		financeAuditLogService.createFinanceAuditLogEntity(fale);

		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(entity.getFinanceId());
		
		
		EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(finance.getEnterpriseId());

		if (DateUtils.daysBetween(DateUtils.now(), DateUtils.fromDateInt(grade.getEffectiveEndDate())) - finance.getLoanTimeLimit() < 0) {
			throw new BusinessException("该企业授信有效截止时间为："+DateUtil.formatDate(DateUtils.fromDateInt(grade.getEffectiveEndDate()))+"，已超过了合理期限，提交失败。");
		}

		if (Boolean.FALSE == financeAudit.getRiskAuditState()) {
			finance.setFinanceState(FinanceStateEnum.APPROVE);
			finance.setConstractState(ConstractStateEnum.UNSUBMIT);
			initFinanceApplication(entity);
			entity.setFinanceAuditState(FinanceAuditEnum.PROCESSING);
			finance.setCallback(Boolean.TRUE);

			//风控审批拒绝，删除箱号信息（融资产品状态为3,5,6）和箱号货物信息
			//1 判断融资产品状态
			int ordinal = finance.getProductType().ordinal();
			if(ordinal == 3 || ordinal == 5 || ordinal == 6) {
				List<FinanceBulkstockEntity> fbes = financeBulkstockService.inquireFinanceBulkstockList(finance.getFinanceId());
				for (FinanceBulkstockEntity fbe : fbes) {
					fbe.setRecieve(BigDecimal.ZERO);
					financeBulkstockService.updateFinanceBulkstockEntity(fbe);
				}
				List<ContainerInventoryEntity> inventoryList = containerInventoryService.inquireEffectiveContainerInventoryList(finance.getFinanceId());
				for (ContainerInventoryEntity containerInventoryEntity : inventoryList) {
					unlockInbound(containerInventoryEntity.getCaseNumber());
					Long inventoryId = containerInventoryEntity.getInventoryId();
					containerInventoryService.deleteContainerInventory(inventoryId);
					//删除货箱货物信息
					List<ContainerBulkstockEntity> containerBulkstockList = containerBulkstockService.inquireContainerBulkstockList(inventoryId);
					for (ContainerBulkstockEntity containerBulkstockEntity : containerBulkstockList) {
						containerBulkstockService.deleteContainerBulkstock(containerBulkstockEntity.getContainerBulkstockId());
					}
				}
			}

			List<FinanceFilesInfoEntity> ffies = financeFilesInfoService.inquireFinanceFilesInfoList(entity.getFinanceId(), null);
			for (FinanceFilesInfoEntity ffie : ffies) {
				for (String fuid : ffie.getFilesUuid().split(",")) {
					SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(fuid);
					if (StringUtil.isBlank(sfie.getFilesSign()) || "0".equals(sfie.getFilesSign())) {
						sfie.setFileSignState(FileSignStateEnum.UNKNOWN);
					} else {
						sfie.setFileSignState(FileSignStateEnum.CLIENT_SIGN);
					}
					signFileInfoService.updateSignFileInfo(sfie);
				}
			}

			//消息推送-业务部
			SendLetterMessage.sendLetterMessage("businessAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "商务审核"));
		} else {
			entity.setFinalState(ApiFinanceStateEnum.FKMANAGE.getCode());
			entity.setRiskSubmitState(Boolean.TRUE);
			//消息推送-风控领导
			SendLetterMessage.sendLetterMessage("riskMemberAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "风控领导审核"));
		}

		entity.setFinanceAuditState(FinanceAuditEnum.PROCESSING);
		financeAuditService.updateFinanceAuditEntity(entity);
		financeApplicationService.updateFinanceApplication(finance);

	}

	@Override
	@Transactional
	public void submitRiskMemberAuditOpinion(FinanceAudit financeAudit) {
		logger.info("wenwenlong=========" + financeAudit);
		if (StringUtil.isBlank(financeAudit.getDeviceType())) {
			supplementRiskMemberAuditOpinion(financeAudit);
		}
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		FinanceAuditEntity entity = financeAuditService.inquireLatestFinanceAudit(financeAudit.getFinanceId());
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(entity.getFinanceId());
		if (Boolean.TRUE == entity.getRiskMemberSubmitState()) {
			throw new BusinessException("审核意见已提交，不能再次修改！");
		}
		
		EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(finance.getEnterpriseId());

		if (DateUtils.daysBetween(DateUtils.now(), DateUtils.fromDateInt(grade.getEffectiveEndDate())) - finance.getLoanTimeLimit() < 0) {
			throw new BusinessException("该企业授信有效截止时间为："+DateUtil.formatDate(DateUtils.fromDateInt(grade.getEffectiveEndDate()))+"，已超过了合理期限，提交失败。");
		}

		FinanceAuditLogEntity fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), financeAudit.getRiskMemberAuditState() ? 1L:0, "风控领导:" + entity.getRiskMemberAudit(), entity.getFinanceId(), 1L,FinanceSessionContext.getAccountId());

		financeAuditLogService.createFinanceAuditLogEntity(fale);
		if (Boolean.FALSE == financeAudit.getRiskMemberAuditState()) {
			finance.setFinanceState(FinanceStateEnum.APPROVE);
			finance.setConstractState(ConstractStateEnum.UNSUBMIT);
			initFinanceApplication(entity);
			entity.setFinanceAuditState(FinanceAuditEnum.PROCESSING);
			finance.setCallback(Boolean.TRUE);

			//风控领导审批拒绝，删除箱号信息（融资产品状态为3,5,6）和箱号货物信息
			//1 判断融资产品状态
			int ordinal = finance.getProductType().ordinal();
			if(ordinal == 3 || ordinal == 5 || ordinal == 6) {
				List<FinanceBulkstockEntity> fbes = financeBulkstockService.inquireFinanceBulkstockList(finance.getFinanceId());
				for (FinanceBulkstockEntity fbe : fbes) {
					fbe.setRecieve(BigDecimal.ZERO);
					financeBulkstockService.updateFinanceBulkstockEntity(fbe);
				}
				List<ContainerInventoryEntity> inventoryList = containerInventoryService.inquireEffectiveContainerInventoryList(finance.getFinanceId());
				for (ContainerInventoryEntity containerInventoryEntity : inventoryList) {
					Long inventoryId = containerInventoryEntity.getInventoryId();
					unlockInbound(containerInventoryEntity.getCaseNumber());
					containerInventoryService.deleteContainerInventory(inventoryId);
					//删除货箱货物信息
					List<ContainerBulkstockEntity> containerBulkstockList = containerBulkstockService.inquireContainerBulkstockList(inventoryId);
					for (ContainerBulkstockEntity containerBulkstockEntity : containerBulkstockList) {
						containerBulkstockService.deleteContainerBulkstock(containerBulkstockEntity.getContainerBulkstockId());
					}
				}
			}

			List<FinanceFilesInfoEntity> ffies = financeFilesInfoService.inquireFinanceFilesInfoList(entity.getFinanceId(), null);
			for (FinanceFilesInfoEntity ffie : ffies) {
				for (String fuid : ffie.getFilesUuid().split(",")) {
					SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(fuid);
					if (StringUtil.isBlank(sfie.getFilesSign()) || "0".equals(sfie.getFilesSign())) {
						sfie.setFileSignState(FileSignStateEnum.UNKNOWN);
					} else {
						sfie.setFileSignState(FileSignStateEnum.CLIENT_SIGN);
					}
					signFileInfoService.updateSignFileInfo(sfie);
				}
			}

			//消息推送
			SendLetterMessage.sendLetterMessage("businessAudit_1", String.format(tmp, finance.getEnterpriseName(), finance.getFinanceNumber(), "商务审核"));
		} else {
			entity.setRiskMemberSubmitState(Boolean.TRUE);

			entity.setFinanceNumber(finance.getFinanceNumber());
			entity.setFinanceAuditState(FinanceAuditEnum.COMPLETED);

			entity.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
			//			auditFinanceApplication(financeAudit, finance, entity);
			consentFinanceApplication(financeAudit);
			FinanceLetterBlockingQueue.putEnterpriseExceptionLetter(finance.getEnterpriseId(), "审批结果", "尊敬的客户：%s，您所发起的融资申请已通过，客服热线:021-6094 5016", finance.getEnterpriseName());

			//货箱补差 - 运费保理
			if (ProductTypeEnum.FREIGHT_FACTORING == finance.getProductType() || ((ProductTypeEnum.PURCHASING == finance.getProductType() || ProductTypeEnum.PURCHASING_STORAGE == finance.getProductType()) && 2 == finance.getSettlementMethod())) {

			} else {
				List<ContainerInventoryEntity> inventories = containerInventoryService.inquireSupervisionFinanceAmountList(finance.getFinanceId());
				BigDecimal fa = BigDecimal.ZERO;
				for (ContainerInventoryEntity cie : inventories) {
					List<ContainerBulkstockEntity> cbes = containerBulkstockService.inquireContainerBulkstockList(cie.getInventoryId());
					for (ContainerBulkstockEntity cbe : cbes) {
						fa = fa.add(cbe.getValuationFinanceAmount());
					}
					//					fa = fa.add(cie.getAdjustment());
				}
				ContainerInventoryEntity last = inventories.get(inventories.size() - 1);
				last.setAdjustment(finance.getFinanceAmount().subtract(fa));
				containerInventoryService.updateContainerInventory(last);
			}

			entity.setRiskMemberSubmitState(Boolean.TRUE);

			List<FinanceCompleteResultEntity> fcres = financeAuditLogService.checkCompleteResultDate(finance.getFinanceId(), ApiTypeEnum.RZ.getCode());
			if (fcres != null && !fcres.isEmpty()) {
				FinanceCompleteResultEntity fcre = fcres.get(0);
				if (fcre != null) {
					fcre.setFinalState(Long.valueOf(FinanceAuditEnum.COMPLETED.ordinal()));
					financeAuditLogService.updateFinanceCompleteResultEntity(fcre);
				}
			}
		}

		financeApplicationService.updateFinanceApplication(finance);
		financeAuditService.updateFinanceAuditEntity(entity);
	}

	@Transactional
	@Override
	public String opposeFinanceApplication(FinanceAudit financeAudit) {
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeAudit.getFinanceId());
		FinanceAuditEntity audit1 = financeAuditService.inquireFinanceAudit(financeAudit.getFinanceAuditId());
		FinanceAuditEntity auditEntity = auditFinanceApplication(financeAudit, financeEntity, audit1);
		financeEntity.setFinanceAmount(BigDecimal.ZERO);
		financeEntity.setFinanceState(FinanceStateEnum.APPROVE_NOPASS);

		// 发送消息
		FinanceLetterBlockingQueue.putEnterpriseFinanceLetter(financeEntity.getEnterpriseId(), "融资审批", "finance.application.nopass", financeEntity.getFinanceNumber());
		// 项目动态
		FinanceProcessEntity financeProcessEntity = FinanceProcessCastor.fromFinanceAuditProcess(financeEntity.getFinanceId(), financeEntity.getFinanceNumber(), auditEntity.getFinanceAuditId());
		financeProcessService.createFinanceProcess(financeProcessEntity);
		financeApplicationService.renovateFinanceApplication(financeEntity);

		return auditEntity.getFinanceAuditId().toString();
	}

	@Transactional
	@Override
	public void consentFinanceAuditAmountApplication(Long financeId) {
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		if (!financeEntity.getEnterpriseId().equals(FinanceSessionContext.getEnterpriseId())) {
			throw new BusinessException("融资信息未找到");
		}
		if (FinanceStateEnum.WAIT_CONFIRM != financeEntity.getFinanceState()) {
			throw new BusinessException("该融资信息不需要审核金额的确认");
		}
		financeEntity.setFinanceState(FinanceStateEnum.WAIT_LOAN);
		financeApplicationService.renovateFinanceApplication(financeEntity);
	}

	@Transactional
	@Override
	public void submitFinanceApplication(Long financeId) {
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		if (FinanceStateEnum.UNSUMIT != financeEntity.getFinanceState()) {
			throw new BusinessException("该融资信息已提交");
		}
		
		financeEntity.setFinanceState(FinanceStateEnum.APPROVE);
		financeApplicationService.renovateFinanceApplication(financeEntity);
		//消息推送-业务审核businessAudit_1
		SendLetterMessage.sendLetterMessage("businessAudit_1", String.format(tmp, financeEntity.getEnterpriseName(), financeEntity.getFinanceNumber(), "商务审核"));
	}

	private void initFinanceApplication(FinanceAuditEntity entity) {
		entity.setFinalState(ApiFinanceStateEnum.YW.getCode());

		entity.setBusinessAudit("");
		entity.setBusinessManageAudit("");
		entity.setRiskAudit("");
		entity.setRiskMemberAudit("");
		entity.setOperationAudit("");
		entity.setOperationManageAudit("");

		entity.setBusinessAuditDate(null);
		entity.setBusinessManageAuditDate(null);
		entity.setRiskAuditDate(null);
		entity.setRiskMemberAuditDate(null);
		entity.setOperationAuditDate(null);
		entity.setOperationManageAuditDate(null);

		entity.setBusinessAuditor("");
		entity.setBusinessManageAuditor("");
		entity.setRiskAuditor("");
		entity.setRiskMemberAuditor("");
		entity.setOperationAuditor("");
		entity.setOperationManageAuditor("");

		entity.setBusinessAuditorId(null);
		entity.setBusinessManageAuditorId(null);
		entity.setRiskAuditorId(null);
		entity.setRiskMemberAuditorId(null);
		entity.setOperationAuditorId(null);
		entity.setOperationManageAuditorId(null);

		entity.setBusinessAuditState(Boolean.TRUE);
		entity.setBusinessManageAuditState(Boolean.TRUE);
		entity.setRiskAuditState(Boolean.TRUE);
		entity.setRiskMemberAuditState(Boolean.TRUE);
		entity.setOperationAuditState(Boolean.TRUE);
		entity.setOperationManageAuditState(Boolean.TRUE);

		entity.setBusinessSubmitState(Boolean.FALSE);
		entity.setBusinessManageSubmitState(Boolean.FALSE);
		entity.setRiskSubmitState(Boolean.FALSE);
		entity.setRiskMemberSubmitState(Boolean.FALSE);
		entity.setOperationSubmitState(Boolean.FALSE);
		entity.setOperationManageSubmitState(Boolean.FALSE);

		entity.setCallback(Boolean.TRUE);
	}

	@Transactional
	@Override
	public void rejectFinanceApplication(Long financeId, String rejectRemark) {
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		financeEntity.setFinanceState(FinanceStateEnum.APPROVE_NOPASS);
		financeEntity.setRejectRemark(rejectRemark);

		// 发送消息
		FinanceLetterBlockingQueue.putEnterpriseFinanceLetter(financeEntity.getEnterpriseId(), "融资审批", "finance.application.reject", financeEntity.getFinanceNumber());
		financeApplicationService.renovateFinanceApplication(financeEntity);
	}

	@Transactional
	@Override
	public void adjustFinanceCreditQuota(Long financeId, BigDecimal creditQuota, Integer adjustment) {
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		if (adjustment == 1) {
			financeEntity.setCreditQuota(creditQuota);
			// 发送消息
			FinanceLetterBlockingQueue.putEnterpriseFinanceLetter(financeEntity.getEnterpriseId(), "融资动态", "finance.application.adjust", financeEntity.getFinanceNumber(), financeEntity.getCreditQuota(), creditQuota);
		} else {
			financeEntity.setBail(creditQuota.add(financeEntity.getBail()));
			// 发送消息
			FinanceLetterBlockingQueue.putEnterpriseFinanceLetter(financeEntity.getEnterpriseId(), "融资动态", "finance.application.adjust1", financeEntity.getFinanceNumber(), financeEntity.getBail(), creditQuota.add(financeEntity.getBail()));
		}

		financeApplicationService.renovateFinanceApplication(financeEntity);
	}

	@Override
	public FinanceApplicationDetail inquireFinanceApplicationDetail(Long financeId) {
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		return FinanceApplicationCastor.toFinanceApplicationDetail(financeEntity);
	}
	

	@Override
	public FinanceApplicationDetail inquireFinanceApplicationDetailByFinanceNUmber(String financeNumber) {
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeNumber);
		if (null == financeEntity) {
			throw new BusinessException("您输入的融资编号不存在！");
		}
		return FinanceApplicationCastor.toFinanceApplicationDetail(financeEntity);
	}

	@Override
	public PageList<FinanceLineInfo> inquireFinanceApplicationList(String dateBegin, String dateEnd, String financeNumber, String bulkstockName, Integer[] financeState, String waybillNumber, String caseNumber, Boolean hasBail, PageCriteria page) {
		FinanceInquireParams params = new FinanceInquireParams();
		params.setBeginDate(DateUtils.formatBeginDay(dateBegin));
		params.setEndDate(DateUtils.formatEndDay(dateEnd));
		params.setFinanceNumber(financeNumber);
		params.setHasBail(hasBail);
		params.setBulkstockName(bulkstockName);
		params.setFinanceState(financeState);
		params.setEnterpriseId(FinanceSessionContext.getEnterpriseId());
		params.setPage(page);
		if (StringUtil.isNotBlank(waybillNumber) || StringUtil.isNotBlank(caseNumber)) {
			List<Long> financeId1s = containerInventoryService.inquireFinanceIdFromContainerInventory(waybillNumber, caseNumber);
			Long[] os = (Long[]) ArrayUtils.addAll(financeId1s.toArray(new Long[financeId1s.size()]), params.getFinanceIds());
			params.setFinanceIds(os);
		}
		if (FinanceSessionContext.isEnterprise()) {
			params.setEnterpriseId(FinanceSessionContext.getEnterpriseId());
		}
		PageList<FinanceApplicationEntity> financeEntities = financeApplicationService.inquireFinanceList(params);
		return FinanceApplicationCastor.toFinanceLineInfo(financeEntities, page);
	}

	@Override
	public PageList<FinanceLineInfo> inquireClientFinanceApplicationList(Long enterpriseId, String dateBegin, String dateEnd, String financeNumber, String bulkstockName, Integer[] financeState, String waybillNumber, String caseNumber, PageCriteria page) {
		if (enterpriseId == null) {
			enterpriseId = FinanceSessionContext.getEnterpriseId();
		}
		FinanceInquireParams params = new FinanceInquireParams();
		EnterpriseCodeEntity code = enterpriseCodeService.inquireEnterpriseCodeDetail(enterpriseId);
		List<Long> enterpriseIds = enterpriseService.conutEnterpriseId(code.getEnterpriseCode());
		params.setEnterpriseIds(enterpriseIds.toArray(new Long[enterpriseIds.size()]));
		params.setBeginDate(DateUtils.formatBeginDay(dateBegin));
		params.setEndDate(DateUtils.formatEndDay(dateEnd));
		params.setFinanceNumber(financeNumber);
		params.setBulkstockName(bulkstockName);
		params.setFinanceState(financeState);
		params.setEnterpriseId(null);
		params.setPage(page);
		if (StringUtil.isNotBlank(waybillNumber) || StringUtil.isNotBlank(caseNumber)) {
			List<Long> financeId1s = containerInventoryService.inquireFinanceIdFromContainerInventory(waybillNumber, caseNumber);//根据/运单号/箱号 获取融资ID列表
			Long[] os = (Long[]) ArrayUtils.addAll(financeId1s.toArray(new Long[financeId1s.size()]), params.getFinanceIds());
			if (os.length == 0) {
				os = new Long[0];
			}
			params.setFinanceIds(os);
		}
		PageList<FinanceApplicationEntity> financeEntities = financeApplicationService.inquireFinanceList(params);
		return FinanceApplicationCastor.toFinanceLineInfo(financeEntities, page);
	}

	@Override
	public PageList<FinanceLineInfo> inquireFinancePadList(String keyword, PageCriteria page) {
		FinanceInquireParams params = new FinanceInquireParams();
		params.setFinanceNumber(keyword);
		params.setPage(page);
		PageList<FinanceApplicationEntity> financeEntities = financeApplicationService.inquireFinanceList(params);
		return FinanceApplicationCastor.toFinanceLineInfo(financeEntities, page);
	}

	@Override
	public PageList<FinanceLineInfo> inquireFinanceList(Long[] financeIds, Long enterpriseId, String enterpriseName, String financeContractNumber, String financeContractSerialNumber, String beginDate, String endDate, BigDecimal minAmount, BigDecimal maxAmount, String financeNumber, String bulkstockName, Long bulkstockInfoId, Integer[] financeState,
			String waybillNumber, String caseNumber, Integer productType, Boolean isProxy, Boolean isWarehouse, PageCriteria page) {
		FinanceInquireParams params = new FinanceInquireParams();
		params.setBeginDate(DateUtils.formatBeginDay(beginDate));
		params.setEndDate(DateUtils.formatEndDay(endDate));
		params.setMaxAmount(maxAmount);
		params.setMinAmount(minAmount);
		params.setFinanceNumber(financeNumber);
		params.setBulkstockName(bulkstockName);
		params.setBulkstockInfoId(bulkstockInfoId);
		params.setFinanceState(financeState);
		params.setEnterpriseName(enterpriseName);
		params.setProductType(productType);
		params.setIsProxy(isProxy);
		params.setIsWarehouse(isWarehouse);
		params.setPage(page);
		if (FinanceSessionContext.isEnterprise()) {
			params.setEnterpriseId(FinanceSessionContext.getEnterpriseId());
		} else {
			params.setEnterpriseId(enterpriseId);
		}
		params.setFinanceIds(financeIds);
		if (StringUtil.isNotBlank(financeContractNumber) || StringUtil.isNotBlank(financeContractSerialNumber)) {
			List<Long> financeId1s = financeContractService.inquireFinanceIdList(financeContractNumber, financeContractSerialNumber);
			if (params.getFinanceIds() != null && params.getFinanceIds().length > 0) {
				Vector<Long> fis = new Vector<>();
				for (Long f : financeId1s) {
					if (Arrays.asList(params.getFinanceIds()).contains(f)){
						fis.add(f);
					}
				}
				params.setFinanceIds(fis.toArray(new Long[fis.size()]));
			} else {
				params.setFinanceIds(financeId1s.toArray(new Long[financeId1s.size()]));
			}
		}

		if (StringUtil.isNotBlank(waybillNumber) || StringUtil.isNotBlank(caseNumber)) {
			List<Long> financeId1s = containerInventoryService.inquireFinanceIdFromContainerInventory(waybillNumber, caseNumber);
			if (params.getFinanceIds() != null && params.getFinanceIds().length > 0) {
				Vector<Long> fis = new Vector<>();
				for (Long f : financeId1s) {
					if (Arrays.asList(params.getFinanceIds()).contains(f)){
						fis.add(f);
					}
				}
				params.setFinanceIds(fis.toArray(new Long[fis.size()]));
			} else {
				params.setFinanceIds(financeId1s.toArray(new Long[financeId1s.size()]));
			}
		}

		PageList<FinanceApplicationEntity> financeEntities = financeApplicationService.inquireFinanceList(params);
		return FinanceApplicationCastor.toFinanceLineInfo(financeEntities, page);
	}

	@Override
	public PageList<FinanceLineInfo> inquireWarehouseFinanceList(Long enterpriseId, String enterpriseName,
			String financeNumber, Integer productType, PageCriteria page) {
		
		PageList<FinanceLineInfo> pages = null;
		StringBuffer sql = new StringBuffer("SELECT count(*) c FROM view_fin_finance_application_list v WHERE 1 = 1");
		
		if (StringUtil.isNotBlank(enterpriseName)) {
			sql.append(" AND v.ENTERPRISE_NAME like '%").append(enterpriseName + "%'");
		}
		
		if (StringUtil.isNotBlank(financeNumber)) {
			sql.append(" AND v.FINANCE_NUMBER like '%").append(financeNumber + "%'");
		}
		
		if (null != productType) {
			sql.append(" AND v.PRODUCT_TYPE =").append(productType);
		}
		
		if (null != enterpriseId) {
			sql.append(" AND v.ENTERPRISE_ID =").append(enterpriseId);
		}
		
		sql.append(" LIMIT " + (page.getPageIndex() - 1)*page.getPageSize() + ", " + page.getPageSize());
		
		logger.info(sql.toString());
		
		Session session = SessionRepository.getCurrentSession();
		List<Object> datas = session.createSQLQuery(sql.toString()).addScalar("c").list();
		for (Object l : datas) {
			Object os = (Object)l;
			pages = new PageList<>(page, ((BigInteger)os).intValue());	
		}
		
		SessionRepository.closeCurrentSession();
		
		sql = new StringBuffer("SELECT * FROM view_fin_finance_application_list v WHERE 1 = 1");
		
		if (StringUtil.isNotBlank(enterpriseName)) {
			sql.append(" AND v.ENTERPRISE_NAME like '%").append(enterpriseName + "%'");
		}
		
		if (StringUtil.isNotBlank(financeNumber)) {
			sql.append(" AND v.FINANCE_NUMBER like '%").append(financeNumber + "%'");
		}
		
		if (null != productType) {
			sql.append(" AND v.PRODUCT_TYPE =").append(productType);
		}
		
		if (null != enterpriseId) {
			sql.append(" AND v.ENTERPRISE_ID =").append(enterpriseId);
		}
		
		sql.append(" LIMIT " + (page.getPageIndex() - 1)*page.getPageSize() + ", " + page.getPageSize());
		
		session = SessionRepository.getCurrentSession();
		datas = session.createSQLQuery(sql.toString()).addScalar("FINANCE_ID").addScalar("FINANCE_NUMBER").addScalar("APPLICATION_DT").addScalar("PRODUCT_TYPE").addScalar("BULKSTOCK_NAME").addScalar("SPECIFICATION").addScalar("TOTAL_LOAN_AMOUNT").addScalar("TOTAL_RECEIVED_AMOUNT").addScalar("AUDIT_INTEREST").addScalar("FINANCE_PRICE").list();
		for (Object l : datas) {
			Object[] os = (Object[])l;
			FinanceLineInfo fli = new FinanceLineInfo();
			fli.setFinanceId(((BigInteger)os[0]).longValue());
			fli.setFinanceNumber((String)os[1]);
			fli.setApplicationDateTime((Date)os[2]);
			fli.setProductType(((Byte)os[3]).intValue());
			
			FinanceBulkstock fb = new FinanceBulkstock();
			fb.setBulkstockName((String)os[4]);
			fb.setSpecification((String)os[5]);
			fb.setFinancePrice((BigDecimal)os[9]);
			
			fli.getBulkstocks().add(fb);
			
			fli.setTotalLoanAmount(((BigDecimal)os[6]).toString());
			fli.setTotalReceivedAmount(((BigDecimal)os[7]).toString());
			fli.setInterest((BigDecimal)os[8]);
			pages.add(fli);
		}
		SessionRepository.closeCurrentSession();
		
		return pages;
	}

	@Override
	public FinanceAuditDetail inquireFinanceLatestAuditDetail(Long financeId) {
		FinanceAuditEntity entity = financeAuditService.inquireLatestFinanceAudit(financeId);
		return FinanceApplicationCastor.toFinanceAuditDetail(entity);
	}

	@Override
	public FinanceAuditDetail inquireFinanceAuditDetail(Long financeAuditId) {
		if (financeAuditId == null || financeAuditId == 0) {
			return null;
		}
		FinanceAuditEntity entity = financeAuditService.inquireFinanceAudit(financeAuditId);
		return FinanceApplicationCastor.toFinanceAuditDetail(entity);
	}

	@Override
	public List<FinanceProcess> inquireFinanceProcessList(Long financeId) {
		List<FinanceProcessEntity> processList = financeProcessService.inquireFinanceProcessList(financeId);
		List<FinanceProcess> resultList = new ArrayList<>();
		for (FinanceProcessEntity entity : processList) {
			resultList.add(FinanceApplicationCastor.toFinanceProcess(entity));
		}
		return resultList;
	}

	// ========================================================================================================================================================//
	@Transactional
	@Override
	public void createFinanceWaybill(Long financeId, String bookingSpaceNumber, String[] waybillNumbers, Integer caseQuantity) {
		if (waybillNumbers == null || waybillNumbers.length == 0) {
			throw new BusinessException("提单号不允许为空");
		}
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		FinanceContainerEntity financeContainer = financeContainerService.inquireFinanceContainer(financeId);
		if (financeContainer == null) {
			financeContainer = new FinanceContainerEntity();
			financeContainer.setFinanceId(financeId);
			financeContainer.setBookingSpaceNumber(bookingSpaceNumber);
			financeContainer.setCaseQuantity(caseQuantity);
			financeContainer.setFinanceNumber(financeEntity.getFinanceNumber());
			financeContainer.setEnterpriseId(financeEntity.getEnterpriseId());
			financeContainer.setEnterpriseName(financeEntity.getEnterpriseName());
			financeContainerService.createFinanceContainer(financeContainer);
		} else {
			financeContainer.setBookingSpaceNumber(bookingSpaceNumber);
			financeContainer.setCaseQuantity(caseQuantity);
			financeContainerService.renovateFinanceContainer(financeContainer);
		}
		List<FinanceContainerWaybillEntity> waybills = financeContainerWaybillService.inquireFinanceContainerWaybillList(financeId);
		for (FinanceContainerWaybillEntity fcwe : waybills) {
			financeContainerWaybillService.deleteFinanceContainerWaybill(fcwe);
		}
		for (String waybillNumber : waybillNumbers) {
			FinanceContainerWaybillEntity entity = new FinanceContainerWaybillEntity();
			entity.setFinanceId(financeId);
			entity.setFinanceNumber(financeContainer.getFinanceNumber());
			entity.setEnterpriseId(financeContainer.getEnterpriseId());
			entity.setEnterpriseName(financeContainer.getEnterpriseName());
			entity.setWaybillNumber(waybillNumber);
			financeContainerWaybillService.createFinanceContainerWaybill(entity);
		}
		financeEntity.setBookingSpace(Boolean.TRUE);
		financeApplicationService.renovateFinanceApplication(financeEntity);
	}

	@Override
	public List<FinanceWaybillDetail> inquireFinanceWaybillList(Long financeId) {
		List<FinanceContainerWaybillEntity> waybills = financeContainerWaybillService.inquireFinanceContainerWaybillList(financeId);
		List<FinanceWaybillDetail> details = new ArrayList<>();
		for (FinanceContainerWaybillEntity entity : waybills) {
			FinanceWaybillDetail detail = new FinanceWaybillDetail();
			BeanUtils.copyProperties(entity, detail);
			details.add(detail);
		}
		return details;
	}

	// ========================================================================================================================================================//
	@Transactional
	@Override
	public String createSupervisionEndall(Long financeId, String remark) {
		FinanceCommissionInfoEntity commission1 = financeCommissionInfoService.inquireFinanceCommissionInfo(financeId);

		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		financeEntity.setFinanceState(FinanceStateEnum.FINISH);
		financeApplicationService.renovateFinanceApplication(financeEntity);
		//		EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(financeEntity.getEnterpriseId());
		//		grade.setCreditAlready(grade.getCreditAlready().subtract(financeEntity.getFinanceAmount()));
		//		enterpriseGradeService.persistEnterpriseGrade(grade);

		FinanceContractEntity financeIdContract = financeContractService.inquireFinanceIdContract(financeId, null);
		// SupervisionContractEntity supervisionContract = supervisionContractService.inquireFinanceIdSupervisionContract(financeId);

		SupervisionEndallEntity entity = new SupervisionEndallEntity();
		entity.setFinanceId(financeId);
		entity.setFinanceNumber(financeEntity.getFinanceNumber());
		entity.setRemark(remark);
		entity.setFinanceContractId(financeIdContract.getFinanceContractId());
		entity.setFinanceContractNumber(financeIdContract.getFinanceContractNumber());
		// entity.setSupervisionContractId(supervisionContract.getSupervisionContractId());
		// entity.setSupervisionContractNumber(supervisionContract.getContractNumber());
		entity.setOperator(FinanceSessionContext.getAccountFullName());
		entity.setOperatorId(FinanceSessionContext.getAccountId());
		Long supervisionEndallId = supervisionEndallService.createSupervisionEndall(entity);

		// 发送消息
		FinanceLetterBlockingQueue.putEnterpriseFinanceLetter(financeEntity.getEnterpriseId(), "项目终结", "finance.application.endall", entity.getFinanceNumber());

		// 项目动态
		FinanceProcessEntity processEntity = FinanceProcessCastor.fromFinanceEndallProcess(financeEntity.getFinanceId(), financeEntity.getFinanceNumber());
		financeProcessService.createFinanceProcess(processEntity);

		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(financeEntity.getEnterpriseId());
		if (commission1 == null && StringUtil.isNotBlank(enterprise.getBelongsEnterpriseCode())) {
			//生成分销商佣金信息
			EnterpriseCodeEntity code = enterpriseCodeService.inquireEnterpriseCodeDetail(enterprise.getBelongsEnterpriseCode(), null);
			EnterpriseEntity enterprise1 = enterpriseService.inquireEnterprise(code.getEnterpriseId());
			List<SupplierCommissionGradeEntity> commissionGrades = supplierCommissionGradeService.inquireSupplierCommissionGradeList(enterprise1.getEnterpriseId());
			FinanceCommissionInfoEntity commission = new FinanceCommissionInfoEntity();
			//			FinanceProductEntity product = financeProductService.inquireFinanceProduct(financeEntity.getProductId());
			FinanceProductInnerEntity product = financeProductInnerService.inquireFinanceProductInner(financeEntity.getFinanceId(), null);
			commission.setFinanceId(financeEntity.getFinanceId());
			commission.setFinanceNumber(financeEntity.getFinanceNumber());
			commission.setProductAnnualRate(product.getInterest());
			commission.setFinanceAmount(financeEntity.getTotalLoanAmount());
			commission.setType(0);
			commission.setAmount(BigDecimal.ZERO);
			commission.setEnterpriseId(enterprise1.getEnterpriseId());
			commission.setEnterpriseName(enterprise1.getEnterpriseName());
			financeCommissionInfoService.createFinanceCommissionInfo(commission);
			for (SupplierCommissionGradeEntity scge : commissionGrades) {
				FinanceExpenseDetailEntity expense = new FinanceExpenseDetailEntity();
				if (product.getInterest().compareTo(scge.getAnnualRateStart()) > 0 && product.getInterest().compareTo(scge.getAnnualRateEnd()) <= 0) {
					expense.setFormula(commission.getFinanceAmount() + "*" + product.getFinanceDays() + "/360*(" + product.getInterest() + "%-10.8%)*" + scge.getExpenseRate() + "%");
					//					expense.setAmount(commission.getFinanceAmount().multiply(new BigDecimal(30/360)).multiply(product.getInterest().subtract(new BigDecimal(10.8))).multiply(scge.getExpenseRate().divide(new BigDecimal(10000))));
					expense.setAmount((commission.getFinanceAmount().multiply(new BigDecimal(product.getFinanceDays())).multiply(product.getInterest().subtract(new BigDecimal(10.8))).multiply(scge.getExpenseRate())).divide(new BigDecimal(3600000), 4, BigDecimal.ROUND_HALF_UP));
					//					(new BigDecimal(product.getFinanceDays()/3600000)).multiply(product.getInterest().subtract(new BigDecimal(10.8))).multiply(scge.getExpenseRate());
					expense.setExpenseRate(scge.getExpenseRate());
				} else {
					continue;
				}
				commission.setAmount(commission.getAmount().add(expense.getAmount()));
				expense.setAmount(commission.getAmount());
				expense.setExpenseItem(scge.getExpenseName());
				commission.setFormula(expense.getFormula());
				expense.setFinanceId(financeId);
				expense.setBillState(Boolean.FALSE);
				financeCommissionInfoService.updateFinanceCommissionInfo(commission);
				financeExpenseDetailService.createFinanceExpenseDetail(expense);
			}
			BigDecimal amount = commission.getAmount();
			BigDecimal rate = BigDecimal.ZERO;
			List<CommissionScaleTableEntity> cstes = commissionScaleTableService.inquireCommissionScaleTable(enterprise.getEnterpriseId(), null);
			for (CommissionScaleTableEntity cste : cstes) {
				FinanceCommissionInfoEntity c = new FinanceCommissionInfoEntity();
				c.setFinanceId(financeEntity.getFinanceId());
				c.setFinanceNumber(financeEntity.getFinanceNumber());
				c.setProductAnnualRate(product.getInterest());
				c.setFinanceAmount(financeEntity.getTotalLoanAmount());
				c.setType(1);
				c.setAccountId(cste.getAccountId());
				c.setName(cste.getName());
				c.setAmount(amount.multiply(cste.getRate().divide(FinanceConstant.HUNDRED, 2, BigDecimal.ROUND_HALF_UP)));
				c.setFormula(commission.getFormula() + "*" + cste.getRate() + "%");
				amount = amount.subtract(c.getAmount());
				rate = rate.add(cste.getRate());
				financeCommissionInfoService.createFinanceCommissionInfo(c);
			}
			commission.setAmount(amount);
			commission.setFormula(commission.getFormula() + "*" + rate + "%");
			financeCommissionInfoService.updateFinanceCommissionInfo(commission);
		}
		return supervisionEndallId.toString();
	}

	@Override
	public SupervisionEndallDetail inquireSupervisionEndall(Long financeId) {
		SupervisionEndallEntity supervisionEndall = supervisionEndallService.inquireFinanceSupervisionEndallEntity(financeId);
		return FinanceApplicationCastor.toSupervisionEndallDetail(supervisionEndall);
	}

	@Override
	@Transactional
	public String createFinanceEvaluate(Long financeId, String content, Integer serviceQuality, Integer deliverySpeed, Integer cargoSecurity, Integer loanSpeed) {
		FinanceApplicationEntity financeEntity = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		financeEntity.setFinanceState(FinanceStateEnum.EVALUATE);
		financeApplicationService.renovateFinanceApplication(financeEntity);

		FinanceEvaluateEntity entity = new FinanceEvaluateEntity();
		entity.setFinanceId(financeId);
		entity.setContent(content);
		entity.setServiceQuality(serviceQuality);
		entity.setDeliverySpeed(deliverySpeed);
		entity.setCargoSecurity(cargoSecurity);
		entity.setLoanSpeed(loanSpeed);
		entity.setFinanceNumber(financeEntity.getFinanceNumber());
		Long evaluateId = financeEvaluateService.createFinanceEvaluate(entity);

		StatisticsEndallEntity see = new StatisticsEndallEntity();
		see.setEnterpriseId(financeEntity.getEnterpriseId());
		see.setEnterpriseName(financeEntity.getEnterpriseName());
		see.setFinanceId(financeEntity.getFinanceId());
		see.setFinanceAmount(financeEntity.getFinanceAmount());
		statisticsEndallService.createStatisticsEndall(see);

//		if (ProductTypeEnum.PROXY_SALE == financeEntity.getProductType() || ProductTypeEnum.PURCHASING_STORAGE == financeEntity.getProductType()) {
//			List<ContainerInventoryEntity> cies = containerInventoryService.inquireContainerInventoryList(financeId, null);
//			for (ContainerInventoryEntity cie : cies) {
//				completeOutbound(cie.getCaseNumber());
//			}
//		}

		return evaluateId.toString();
	}

	@Transactional
	@Override
	public FinanceEvaluateDetail inquireFinanceEvaluate(Long financeId) {
		FinanceEvaluateEntity evaluate = financeEvaluateService.inquireFinanceIdEvaluate(financeId);
		FinanceEvaluateDetail info = new FinanceEvaluateDetail();
		BeanUtils.copyProperties(evaluate, info);
		return info;
	}

	@Override
	public PageList<FinanceEvaluateDetail> inquireFinanceEvaluatePageList(Long financeId, Long enterpriseId, Long logisticsCompanyId, PageCriteria page) {
		PageList<FinanceEvaluateEntity> pageList = financeEvaluateService.inquireFinanceEvaluatePageList(financeId, enterpriseId, logisticsCompanyId, true, page);
		PageList<FinanceEvaluateDetail> resultList = new PageList<>(page, pageList.getTotalRecordCount());
		for (FinanceEvaluateEntity entity : pageList) {
			FinanceEvaluateDetail info = new FinanceEvaluateDetail();
			BeanUtils.copyProperties(entity, info);
			resultList.add(info);
		}
		return resultList;
	}

	@Override
	public String createFinanceCutLines(Long financeId, BigDecimal newLines, String cutReason, String remark) {
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		FinanceCutLinesEntity entity = new FinanceCutLinesEntity();
		entity.setFinanceId(financeId);
		entity.setNewLines(newLines);
		entity.setOldLines(finance.getFinanceAmount());
		entity.setCutReason(cutReason);
		entity.setRemark(remark);
		entity.setCreateDateTime(DateUtil.now());
		entity.setAuditState(AuditStateEnum.UNAUDIT);
		entity.setOperator(FinanceSessionContext.getAccountFullName());
		financeCutLinesService.createFinanceCutLines(entity);
		return entity.getCutId().toString();
	}

	@Override
	@Transactional
	public void auditFinanceCutLines(Long cutId, Integer auditState, String auditRemark) {
		List<ContainerInventoryEntity> containers = new ArrayList<>();
		FinanceCutLinesEntity cutLines = financeCutLinesService.inquireFinanceCutLines(cutId);
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(cutLines.getFinanceId());
		BigDecimal sourceFinanceAmount = finance.getFinanceAmount(); // 原融资金额
		BigDecimal targetFinanceAmount = cutLines.getNewLines(); // 调整后融资金额
		if (auditState == 3) {
			cutLines.setAuditState(AuditStateEnum.REFUSE);
		} else if (auditState == 2) {
			containers = containerInventoryService.inquireEffectiveContainerInventoryList(cutLines.getFinanceId());
			for (ContainerInventoryEntity cie : containers) {
				if (cie.getLoanNoticeId() != null) {
					throw new BusinessException("已经存在执行放款的箱信息,不允许调整融资金额");
				}
			}
			cutLines.setAuditState(AuditStateEnum.PASS);
			cutLines.setOldLines(finance.getFinanceAmount());
			finance.setFinanceAmount(cutLines.getNewLines());
			financeApplicationService.renovateFinanceApplication(finance);
			// 发送消息
			FinanceLetterBlockingQueue.putEnterpriseFinanceLetter(finance.getEnterpriseId(), "融资金额调整", "finance.amount.cutline", finance.getFinanceNumber(), sourceFinanceAmount, targetFinanceAmount);
		}
		cutLines.setAuditDateTime(DateUtil.now());
		cutLines.setAuditor(FinanceSessionContext.getAccountFullName());
		cutLines.setAuditRemark(auditRemark);
		financeCutLinesService.updateFinanceCutLines(cutLines);
		if (auditState == 3) {
			return;
		}
		BigDecimal evaluateAmount = BigDecimal.ZERO;
		List<FinanceBulkstockEntity> financeBulkstocks = financeBulkstockService.inquireFinanceBulkstockList(cutLines.getFinanceId());
		Map<Long, FinanceBulkstockEntity> financeBulkstockMap = new HashMap<>();
		for (FinanceBulkstockEntity bulkstock : financeBulkstocks) {
			evaluateAmount = evaluateAmount.add(bulkstock.getEvaluatePrice().multiply(bulkstock.getValuationQuantity()));
			financeBulkstockMap.put(bulkstock.getBulkstockId(), bulkstock);
		}
		for (FinanceBulkstockEntity bulkstock : financeBulkstocks) {
			bulkstock.setFinancePrice(bulkstock.getEvaluatePrice().multiply(sourceFinanceAmount).divide(evaluateAmount, 2, RoundingMode.HALF_UP)); // 融资单价=估值单价/全部货物估值总额*融资金额
			financeBulkstockService.renovateFinanceBulkstock(bulkstock);
		}
		List<ContainerBulkstockEntity> cbes = containerBulkstockService.inquireContainerBulkstockListByFinanceId(cutLines.getFinanceId());
		for (ContainerBulkstockEntity cbe : cbes) {
			cbe.setFinancePrice(financeBulkstockMap.get(cbe.getBulkstockId()).getFinancePrice());
			containerBulkstockService.renovateContainerBulkstock(cbe);
		}
		FinanceContainerEntity container = financeContainerService.inquireFinanceContainer(finance.getFinanceId());
		if (container != null && container.getCaseQuantity() != null && container.getCaseQuantity().intValue() <= containers.size()) { // 判断是否箱已经收货确认，调整了尾箱差价
			boolean comfirm = true;
			for (ContainerInventoryEntity cie : containers) {
				if (cie.getSupervisionState() == SupervisionStateEnum.ALREADY_REPORT || cie.getSupervisionState() == SupervisionStateEnum.UNKNOWN) { // 还未确认收货,说明未进行尾箱调价
					comfirm = false;
					break;
				}
			}
			if (comfirm) { // 需尾箱调价
				BigDecimal caculateFinanceAmount = targetFinanceAmount;
				for (int i = 0; i < containers.size(); i++) {
					ContainerInventoryEntity cie = containers.get(i);
					for (ContainerBulkstockEntity cbe : cbes) {
						if (cbe.getInventoryId().equals(cie.getInventoryId())) {
							caculateFinanceAmount = caculateFinanceAmount.subtract(cbe.getValuationFinanceAmount());
						}
					}
					caculateFinanceAmount = caculateFinanceAmount.subtract(cie.getAdjustment());
					if (i == containers.size() - 1) { // 最后一个箱
						cie.setAdjustment(cie.getAdjustment().add(caculateFinanceAmount));
						containerInventoryService.renovateContainerInventory(cie);
					}
				}
			}
		}
	}

	@Override
	public PageList<FinanceCutLinesDetail> inquireFinanceCutLinesPageList(Long financeId, PageCriteria page) {
		PageList<FinanceCutLinesEntity> pages = financeCutLinesService.inquireFinanceCutLinesPageList(financeId, page);
		PageList<FinanceCutLinesDetail> results = new PageList<FinanceCutLinesDetail>(page, pages.getTotalRecordCount());
		for (FinanceCutLinesEntity fcle : pages) {
			FinanceCutLinesDetail detail = FinanceApplicationCastor.toFinanceCutLinesDetail(fcle);
			results.add(detail);
		}
		return results;
	}

	@Override
	public FinanceCutLinesDetail inquireFinanceCutLinesDetail(Long cutId) {
		FinanceCutLinesEntity entity = financeCutLinesService.inquireFinanceCutLines(cutId);
		FinanceCutLinesDetail detail = FinanceApplicationCastor.toFinanceCutLinesDetail(entity);
		return detail;
	}

	@Override
	public HandleSuitcaseResult handleSuitcase(String waybillNumber, String caseNumber) {
		final String HANDLE_SUITCASE_KEY = "HKdj67s7hhjQKCNVfggr4242ftasdSFDGS";
		String url = ConfigPropertites.getProperties("finance.handleSuitcase.service");
		HandleSuitcaseResult result = new HandleSuitcaseResult();

		Map<String, String> params = new HashMap<>();
		params.put("billNumber", waybillNumber);
		params.put("boxNumbers", caseNumber);
		params.put("key", HANDLE_SUITCASE_KEY);
		params.put("state", 0 + "");
		String responseText = HttpClientHelper.post(url, params);

		if (responseText == null) {
			throw new BusinessException("查询信息失败！");
		}

		result = JSON.toBean(responseText, HandleSuitcaseResult.class);
		return result;
	}

	@Override
	public HandleSuitcaseResult changeOrderInfo(String bookingSpaceNumber, String financeNumber, Integer type) {
		type = type == null ? 1 : type;
		final String HANDLE_SUITCASE_KEY = "HKdj67s7hhjQKCNVfggr4242ftasdSFDGS";
		String url = ConfigPropertites.getProperties("finance.changeOrderInfo.service");
		HandleSuitcaseResult result = new HandleSuitcaseResult();

		Map<String, String> params = new HashMap<>();
		params.put("orderNo", bookingSpaceNumber);
		params.put("financingOrder", financeNumber);
		params.put("key", HANDLE_SUITCASE_KEY);
		params.put("type", type.toString());
		String responseText = HttpClientHelper.post(url, params);
		System.out.println(responseText);
		result = JSON.toBean(responseText, HandleSuitcaseResult.class);
		return result;
	}

	@Override
	public HandleSuitcaseResult selectStatus(String waybillNumber, String caseNumber) {
		final String HANDLE_SUITCASE_KEY = "HKdj67s7hhjQKCNVfggr4242ftasdSFDGS";
		String url = ConfigPropertites.getProperties("finance.selectStatus.service");
		HandleSuitcaseResult result = new HandleSuitcaseResult();

		Map<String, String> params = new HashMap<>();
		params.put("billNumber", waybillNumber);
		params.put("boxNumbers", caseNumber);
		params.put("key", HANDLE_SUITCASE_KEY);
		String responseText = HttpClientHelper.post(url, params);

		if (responseText == null) {
			throw new BusinessException("查询信息失败！");
		}

		result = JSON.toBean(responseText, HandleSuitcaseResult.class);
		return result;
	}

	@Override
	public List<FinanceBulkstock> getPODetail(String bookingSpaceNumber, String userId) {
		String url = ConfigPropertites.getProperties("finance.getPODetail.service");
		Map<String, String> params = new HashMap<>();
		params.put("PONO", bookingSpaceNumber);
		params.put("userID", userId);
		String responseText = HttpClientHelper.post(url, params);

		if (responseText == null) {
			throw new BusinessException("查询信息失败！");
		}

		List<FinanceBulkstock> list = new ArrayList<>();
		JSONObject json = JSONObject.fromObject(responseText);
		FinanceBulkstock bulkstock = new FinanceBulkstock();
		BulkstockInfoEntity bulkstockInfoEntity = bulkstockInfoService.inquireBulkstockInfo(json.getJSONObject("POHead").getString("goodsName"));
		bulkstock.setBulkstockName(bulkstockInfoEntity.getBulkstockName());
		bulkstock.setSpecification(bulkstockInfoEntity.getSpecificationName());
		bulkstock.setBulkstockInfoId(bulkstockInfoEntity.getBulkstockInfoId());
		bulkstock.setBulkstockCategoryId(bulkstockInfoEntity.getBulkstockCategoryId());
		bulkstock.setQuantity(new BigDecimal(json.getJSONObject("POHead").getString("goodsQuantity")));
		bulkstock.setWeight(new BigDecimal(json.getJSONObject("POHead").getString("goodsWeight")));
		bulkstock.setVolume(json.getJSONObject("POHead").getString("goodsVolume"));
		bulkstock.setUnit("批");
		bulkstock.setOriginPlace("国内");
		list.add(bulkstock);

		return list;
	}

	@Override
	@Transactional
	public HandleSuitcaseResult goldLocked(String waybillNumber, String caseNumber) {
		HandleSuitcaseResult result = new HandleSuitcaseResult();

		Map<String, String> params = new HashMap<>();
		params.put("billNumber", waybillNumber);
		params.put("boxNumbers", caseNumber);
		params.put("Key", FinanceConstant.HANDLE_SUITCASE_KEY);

		String url = ConfigPropertites.getProperties("financialPlatformService");
		String responseText = ServiceClientHelper.invoke(url, "goldLocked", params);
		result = JSON.toBean(responseText, HandleSuitcaseResult.class);
		logger.info("================"+responseText);
		logger.info("Message:" + result.getMessage() + ",result:" + result.getResult());
		//增加加锁信息
		FinanceLockedInfoEntity financeLockedInfoEntity = new FinanceLockedInfoEntity();
		financeLockedInfoEntity.setWaybillNumber(waybillNumber);
		financeLockedInfoEntity.setCaseNumber(caseNumber);
		financeLockedInfoEntity.setRemarkInfo("加锁：" + result.getMessage());
		financeLockedInfoEntity.setOperateTime(DateUtil.now());
		financeLockedInfoService.createLockedInfo(financeLockedInfoEntity);
		if (Boolean.FALSE == result.getResult()) {
			throw new BusinessException(result.getMessage());
		}
		return result;
	}

	@Transactional
	public HandleSuitcaseResult goldLocked(Long inventoryId) {
		ContainerInventoryEntity cie = containerInventoryService.inquireContainerInventory(inventoryId);
		if (cie == null) {
			throw new BusinessException("该货箱不存在!");
		}

		HandleSuitcaseResult result = new HandleSuitcaseResult();

		Map<String, String> params = new HashMap<>();
		params.put("billNumber", cie.getWaybillNumber());
		params.put("boxNumbers", cie.getCaseNumber());
		params.put("Key", FinanceConstant.HANDLE_SUITCASE_KEY);

		String url = ConfigPropertites.getProperties("financialPlatformService");
		String responseText = ServiceClientHelper.invoke(url, "goldLocked", params);
		result = JSON.toBean(responseText, HandleSuitcaseResult.class);
		if (result != null) {
			logger.info("================"+responseText);
			logger.info("Message:" + result.getMessage() + ",result:" + result.getResult());
			//增加加锁信息
			FinanceLockedInfoEntity financeLockedInfoEntity = new FinanceLockedInfoEntity();
			financeLockedInfoEntity.setWaybillNumber(cie.getWaybillNumber());
			financeLockedInfoEntity.setCaseNumber(cie.getCaseNumber());
			financeLockedInfoEntity.setRemarkInfo("加锁：" + result.getMessage());
			financeLockedInfoEntity.setOperateTime(DateUtil.now());
			financeLockedInfoService.createLockedInfo(financeLockedInfoEntity);
		}

		return result;
	}

	@Override
	@Transactional
	public HandleSuitcaseResult goldUnlocked(String waybillNumber, String caseNumber) {
		HandleSuitcaseResult result = new HandleSuitcaseResult();

		Map<String, String> params = new HashMap<>();
		params.put("billNumber", waybillNumber);
		params.put("boxNumbers", caseNumber);
		params.put("state", String.valueOf(0));
		params.put("Key", FinanceConstant.HANDLE_SUITCASE_KEY);

		String url = ConfigPropertites.getProperties("financialPlatformService");
		String responseText = ServiceClientHelper.invoke(url, "goldUnlocked", params);
		logger.info("================"+responseText);
		//增加解锁信息
		FinanceLockedInfoEntity financeLockedInfoEntity = new FinanceLockedInfoEntity();
		financeLockedInfoEntity.setWaybillNumber(waybillNumber);
		financeLockedInfoEntity.setCaseNumber(caseNumber);
		financeLockedInfoEntity.setRemarkInfo("解锁：" + result.getMessage());
		financeLockedInfoEntity.setOperateTime(DateUtil.now());
		financeLockedInfoService.createLockedInfo(financeLockedInfoEntity);

		result = JSON.toBean(responseText, HandleSuitcaseResult.class);
		return result;
	}

	public HandleSuitcaseResult goldUnlocked(Long inventoryId) {
		ContainerInventoryEntity cie = containerInventoryService.inquireContainerInventory(inventoryId);
		if (cie == null) {
			throw new BusinessException("该货箱不存在!");
		}
		HandleSuitcaseResult result = new HandleSuitcaseResult();

		Map<String, String> params = new HashMap<>();
		params.put("billNumber", cie.getWaybillNumber());
		params.put("boxNumbers", cie.getCaseNumber());
		params.put("state", String.valueOf(0));
		params.put("Key", FinanceConstant.HANDLE_SUITCASE_KEY);

		String url = ConfigPropertites.getProperties("financialPlatformService");
		String responseText = ServiceClientHelper.invoke(url, "goldUnlocked", params);
		System.out.println(responseText);

		result = JSON.toBean(responseText, HandleSuitcaseResult.class);
		return result;
	}

	@Override
	public HandleSuitcaseResult containerTaken(String waybillNumber, String caseNumber) {
		HandleSuitcaseResult result = new HandleSuitcaseResult();

		Map<String, String> params = new HashMap<>();
		params.put("billNumber", waybillNumber);
		params.put("boxNumbers", caseNumber);
		params.put("Key", FinanceConstant.HANDLE_SUITCASE_KEY);

		String url = ConfigPropertites.getProperties("financialPlatformService");
		String responseText = ServiceClientHelper.invoke(url, "containerTaken", params);
		logger.info("wenwenlong"+responseText);
		if (null == responseText) {
			responseText = "";
		}
		result = JSON.toBean(responseText, HandleSuitcaseResult.class);
		return result;
	}

	@Override
	public PageList<FinanceCommissionInfoDetail> inquireFinanceCommissionInfoPageList(Long extractId, Long enterpriseId, Long accountId, Integer type, PageCriteria page) {
		if (enterpriseId == null) {
			enterpriseId = FinanceSessionContext.getEnterpriseId();
		}
		PageList<FinanceCommissionInfoEntity> pages = financeCommissionInfoService.inquireFinanceCommissionInfoPageList(extractId, enterpriseId, accountId, type, page);
		PageList<FinanceCommissionInfoDetail> resulst = new PageList<>(page, pages.getTotalRecordCount());
		for (FinanceCommissionInfoEntity fcie : pages) {
			FinanceCommissionInfoDetail detail = new FinanceCommissionInfoDetail();
			BeanUtils.copyProperties(fcie, detail);
			resulst.add(detail);
		}
		return resulst;
	}

	@Override
	public List<FinanceCommissionInfoDetail> inquireFinanceCommissionInfoList(Long extractId) {
		List<FinanceCommissionInfoEntity> list = financeCommissionInfoService.inquireFinanceCommissionInfoList(extractId);
		List<FinanceCommissionInfoDetail> resulst = new ArrayList<>();
		for (FinanceCommissionInfoEntity fcie : list) {
			FinanceCommissionInfoDetail detail = new FinanceCommissionInfoDetail();
			BeanUtils.copyProperties(fcie, detail);
			resulst.add(detail);
		}
		return resulst;
	}

	@Override
	public PageList<FinanceExpenseDetail> inquireFinanceExpenseDetailPageList(Long financeId, String expenseItem, PageCriteria page) {
		PageList<FinanceExpenseDetailEntity> pages = financeExpenseDetailService.inqurieFinanceExpenseDetailPageList(financeId, expenseItem, page);
		PageList<FinanceExpenseDetail> resulst = new PageList<>(page, pages.getTotalRecordCount());
		for (FinanceExpenseDetailEntity fede : pages) {
			FinanceExpenseDetail detail = new FinanceExpenseDetail();
			BeanUtils.copyProperties(fede, detail);
			resulst.add(detail);
		}
		return resulst;
	}

	@Override
	@Transactional
	public void createFinanceMoneyStatementEarning(Long[] financeIds) {
		CommissionExtractApplicationEntity extract = new CommissionExtractApplicationEntity();
		extract.setApplicant(FinanceSessionContext.getAccountFullName());
		extract.setApplicationDatetime(DateUtils.now());
		extract.setAuditState(AuditStateEnum.UNAUDIT);
		commissionExtractApplicationService.createCommissionExtractApplication(extract);
		for (Long financeId : financeIds) {
			FinanceCommissionInfoEntity entity = financeCommissionInfoService.inquireFinanceCommissionInfo(financeId);
			if (entity.getExtractId() != null) {
				throw new BusinessException("融资编号为:" + entity.getFinanceNumber() + "的融资已申请提取佣金");
			}
			entity.setExtractId(extract.getExtractId());
			financeCommissionInfoService.updateFinanceCommissionInfo(entity);
			extract.setEnterpriseId(entity.getEnterpriseId());
		}
		commissionExtractApplicationService.updateCommissionExtractApplication(extract);
	}

	@Override
	@Transactional
	public void createFinanceMoneyStatementBill(Long expenseDetailId) {
		// TODO Auto-generated method stub

	}

	@Override
	public PageList<CommissionExtractApplicationDetail> inquireCommissionExtractApplicationPageList(Integer auditState, PageCriteria page) {
		PageList<CommissionExtractApplicationEntity> pages = commissionExtractApplicationService.inquireCommissionExtractApplicationPageList(auditState, page);
		PageList<CommissionExtractApplicationDetail> resulsts = new PageList<>(page, pages.getTotalRecordCount());
		for (CommissionExtractApplicationEntity ceae : pages) {
			List<FinanceCommissionInfoEntity> commissions = financeCommissionInfoService.inquireFinanceCommissionInfoList(ceae.getExtractId());
			BigDecimal amount = BigDecimal.ZERO;
			for (FinanceCommissionInfoEntity fcie : commissions) {
				amount = amount.add(fcie.getAmount());
			}
			CommissionExtractApplicationDetail detail = new CommissionExtractApplicationDetail();
			EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(ceae.getEnterpriseId());
			BeanUtils.copyProperties(ceae, detail);
			detail.setAuditState(ceae.getAuditState().ordinal());
			if (enterprise != null) {
				detail.setEnterpriseName(enterprise.getEnterpriseName());
			}
			detail.setAmount(amount);
			resulsts.add(detail);
		}
		return resulsts;
	}

	@Override
	public CommissionExtractApplicationDetail inquireCommissionExtractApplicationDetail(Long extractId) {
		CommissionExtractApplicationEntity entity = commissionExtractApplicationService.inquireCommissionExtractApplication(extractId);
		List<FinanceCommissionInfoEntity> commissions = financeCommissionInfoService.inquireFinanceCommissionInfoList(entity.getExtractId());
		BigDecimal amount = BigDecimal.ZERO;
		for (FinanceCommissionInfoEntity fcie : commissions) {
			amount = amount.add(fcie.getAmount());
		}
		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(entity.getEnterpriseId());
		CommissionExtractApplicationDetail detail = new CommissionExtractApplicationDetail();
		BeanUtils.copyProperties(entity, detail);
		detail.setEnterpriseName(enterprise.getEnterpriseName());
		detail.setAuditState(entity.getAuditState().ordinal());
		detail.setAmount(amount);
		return detail;
	}

	@Override
	public void saveCommissionExtractApplicationAudit(Long extractId, Integer auditType, Boolean auditState,
			String audit) {
		CommissionExtractApplicationEntity entity = commissionExtractApplicationService.inquireCommissionExtractApplication(extractId);
		switch (auditType) {
		case 1:
			if (entity.getAuditSubmitState1() != null && entity.getAuditSubmitState1()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit1(audit);
			entity.setAuditState1(auditState);
			entity.setAuditDate1(DateUtil.now());
			entity.setAuditor1(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId1(FinanceSessionContext.getAccountId());
			break;
		case 2:
			if (entity.getAuditSubmitState2() != null && entity.getAuditSubmitState2()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit2(audit);
			entity.setAuditState2(auditState);
			entity.setAuditDate2(DateUtil.now());
			entity.setAuditor2(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId2(FinanceSessionContext.getAccountId());
			break;
		default:
			break;
		}
		commissionExtractApplicationService.updateCommissionExtractApplication(entity);
	}

	@Override
	public void submitCommissionExtractApplicationAudit(Long extractId, Integer auditType) {
		CommissionExtractApplicationEntity entity = commissionExtractApplicationService.inquireCommissionExtractApplication(extractId);
		switch (auditType) {
		case 1:
			entity.setAuditSubmitState1(Boolean.TRUE);
			break;
		case 2:
			entity.setAuditSubmitState2(Boolean.TRUE);
			break;
		default:
			break;
		}
		commissionExtractApplicationService.updateCommissionExtractApplication(entity);
	}

	@Override
	public void consentCommissionExtractApplication(Long extractId) {
		CommissionExtractApplicationEntity entity = commissionExtractApplicationService.inquireCommissionExtractApplication(extractId);
		entity.setAuditState(AuditStateEnum.PASS);
		commissionExtractApplicationService.updateCommissionExtractApplication(entity);
		List<FinanceCommissionInfoEntity> commissions = financeCommissionInfoService.inquireFinanceCommissionInfoList(extractId);
		BigDecimal amount = BigDecimal.ZERO;
		Long financeId = 0L;
		String financeNumber = "";
		for (FinanceCommissionInfoEntity fcie : commissions) {
			financeId = fcie.getFinanceId();
			financeNumber = fcie.getFinanceNumber();
			amount = amount.add(fcie.getAmount());
		}

		FinanceMoneyStatementEntity moneyEntity = new FinanceMoneyStatementEntity();

		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(entity.getEnterpriseId());
		moneyEntity.setFinanceId(financeId);
		moneyEntity.setFinanceNumber(financeNumber);
		moneyEntity.setAmount(amount);
		moneyEntity.setCreateDateTime(DateUtils.now());
		moneyEntity.setReceiptId(enterprise.getEnterpriseId());
		moneyEntity.setStatementDate(DateUtil.parseDateInt(entity.getApplicationDatetime().toString()));
		moneyEntity.setReceiptName(enterprise.getEnterpriseName());
		moneyEntity.setReceiptType(OperatorRoleEnum.ENTERPRISE.ordinal());
		moneyEntity.setReceiptTenantId(enterprise.getTenantId());;
		moneyEntity.setDisbursementType(OperatorRoleEnum.PLATFORM.ordinal());
		moneyEntity.setDisbursementName(ConfigPropertites.getProperties("platform.name"));
		moneyEntity.setDisbursementTenantId(FinanceConstant.DEFAULT_PLATFORM_WEB_TENANT);
		moneyEntity.setStatementSource("COMMISSION_SETTLEMENT");
		moneyEntity.setStatementState(StatementStateEnum.PAID);
		moneyEntity.setStatementSourceId(extractId);
		financeMoneyStatementService.createFinanceMoneyStatement(moneyEntity);
	}

	@Override
	public void opposeCommissionExtractApplication(Long extractId) {
		CommissionExtractApplicationEntity entity = commissionExtractApplicationService.inquireCommissionExtractApplication(extractId);
		entity.setAuditState(AuditStateEnum.REFUSE);
		commissionExtractApplicationService.updateCommissionExtractApplication(entity);

		List<FinanceCommissionInfoEntity> commissions = financeCommissionInfoService.inquireFinanceCommissionInfoList(extractId);
		for (FinanceCommissionInfoEntity fcie : commissions) {
			fcie.setExtractId(null);
			financeCommissionInfoService.updateFinanceCommissionInfo(fcie);
		}
	}

	@Override
	public List<FinanceAuditRecordDetail> inquireAuditRecord(Long recordType, Long auditId) {
		List<FinanceAuditRecordDetail> fards = new ArrayList<>();
		List<FinanceAuditLogEntity> fales = financeAuditLogService.inquireFinanceAuditLogList(auditId, recordType);
		for (FinanceAuditLogEntity fale : fales) {
			FinanceAuditRecordDetail fard = new FinanceAuditRecordDetail();
			BeanUtils.copyProperties(fale, fard);
			AccountEntity ae = accountService.inquireAccountDetail(fale.getAccountId());
			fard.setAccountName(ae.getFullName());
			fards.add(fard);
		}

		return fards;
	}

	@Override
	@Transactional
	public String createFinanceCancelApplication(Long financeId, String remark) {
		List<LoanNoticeEntity> lnes = loanNoticeService.inquireLoanNoticeList(financeId);
		if (lnes == null || lnes.size() > 0) {
			throw new BusinessException("改融资已放款，不能取消!");
		}

		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		FinanceCancelApplicationEntity entity = new FinanceCancelApplicationEntity();
		if (FinanceSessionContext.isEnterprise()) {
			entity.setApplicationAuthor(FinanceSessionContext.getEnterpriseName());
		} else {
			entity.setApplicationAuthor(FinanceSessionContext.getAccountFullName());
		}
		entity.setFinanceId(financeId);
		entity.setRemark(remark);
		entity.setFinanceNumber(finance.getFinanceNumber());

		financeCancelApplicationService.createFinanceCancelApplication(entity);
		return entity.getCancelId().toString();
	}

	@Override
	public PageList<FinanceCancelApplicationDetail> inquireFinanceCancelApplicationPageList(PageCriteria page) {
		PageList<FinanceCancelApplicationEntity> pages = financeCancelApplicationService.inquireFinanceCancelApplicationPageList(page);
		PageList<FinanceCancelApplicationDetail> results = new PageList<>(page, pages.getTotalRecordCount());
		for (FinanceCancelApplicationEntity fcae : pages) {
			FinanceCancelApplicationDetail detail = new FinanceCancelApplicationDetail();
			BeanUtils.copyProperties(fcae, detail);
			FinanceContractEntity fce = financeContractService.inquireFinanceIdContract(fcae.getFinanceId(), null);
			FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(fcae.getFinanceId());
			if (fce != null) {
				detail.setFinanceContractSerialNumber(fce.getFinanceContractSerialNumber());
			}
			if (finance != null) {
				detail.setEnterpriseName(finance.getEnterpriseName());
			}
			detail.setAuditState1(fcae.getAuditState1().ordinal());
			results.add(detail);
		}
		return results;
	}

	@Override
	@Transactional
	public void auditFinanceCancelApplication(Long cancelId, Integer auditState, String auditRemark) {
		FinanceCancelApplicationEntity entity = financeCancelApplicationService.inquireFinanceCancelApplication(cancelId);
		FinanceApplicationEntity fae = financeApplicationService.inquireFinanceApplicationEntity(entity.getFinanceId());
		entity.setAuditor1(FinanceSessionContext.getAccountFullName());
		entity.setAuditorId1(FinanceSessionContext.getAccountId());
		entity.setAuditRemark1(auditRemark);
		entity.setAuditState1(AuditStateEnum.valueOf(auditState));
		if (AuditStateEnum.PASS == entity.getAuditState1()) {
			List<ContainerInventoryEntity> cies = containerInventoryService.inquireContainerInventoryList(entity.getFinanceId(), null);
			for (ContainerInventoryEntity cie :  cies) {
				cie.setSignState(Boolean.TRUE);
				cie.setAbnormal(Boolean.TRUE);
				cie.setSupervisionState(SupervisionStateEnum.ALREADY_SUPERVISE);
				if (cie.getLoanNoticeId() != null && cie.getLoanNoticeId() != 0L) {
					throw new BusinessException("已放款的融资不能取消！");
				}
				containerInventoryService.updateContainerInventory(cie);

				//解锁
				if (1L == cie.getLogisticsCompanyInfoId()) {
					HandleSuitcaseResult result = goldUnlocked(cie.getWaybillNumber(), cie.getCaseNumber());
					FinanceContainerLogEntity fcle = new FinanceContainerLogEntity();
					fcle.setInventoryId(cie.getInventoryId());
					fcle.setOperator(FinanceSessionContext.getAccountFullName());
					if (result != null) {
						fcle.setRemark("解锁 " + result.getMessage());
					} else {
						fcle.setRemark("解锁失败");
					}
					financeContainerLogService.createFinanceContainerLog(fcle);
				} else {
					if (ProductTypeEnum.PURCHASING_STORAGE == fae.getProductType() || ProductTypeEnum.PROXY_SALE == fae.getProductType()) {
						unlockInbound(cie.getCaseNumber());
					}
				}
				//				logger.info("Message" + result.getMessage() + ",result" + result.getResult());
			}
			FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(entity.getFinanceId());
			finance.setFinanceState(FinanceStateEnum.CANCEL);
			financeApplicationService.updateFinanceApplication(finance);
		}

		financeCancelApplicationService.updateFinanceCancelApplication(entity);
	}

	@Override
	public String inquireFinanceState() {
		StringBuffer sb = new StringBuffer();
		for (FinanceStateEnum f : FinanceStateEnum.values()) {
			sb.append(f.getValue() + ",");
		}
		if (sb.length()>0) {
			sb.deleteCharAt(sb.length()-1);
		}
		return sb.toString();
	}

	@Override
	public List<WarehouseInfo> inquireWarehouseList(String enterpriseId) {
		String url = ConfigPropertites.getProperties("finance.returnWarehouse.service");
		Map<String, String> params = new HashMap<>();
		if (StringUtil.isNotBlank(enterpriseId)) {
			params.put("cust_id", enterpriseId);
		}
		params.put("enterpriseId", "YIRUNWMS");
		System.out.println(params);
		String responseText = HttpClientHelper.post(url, params);
		System.out.println("responseText:" + responseText);
		JSONArray jArray= JSONArray.fromObject(responseText);
		Collection<?> collection = JSONArray.toCollection(jArray, WarehouseInfo.class);
		List<WarehouseInfo> whis = new ArrayList<WarehouseInfo>();
		Iterator<?> it = collection.iterator();
		while (it.hasNext()) {
			WarehouseInfo user = (WarehouseInfo) it.next();
			whis.add(user);
		}

		return whis;
	}

	@Override
	public List<WarehouseInfo> inquireWarehouseCustList() {
		String url = ConfigPropertites.getProperties("finance.returnWarehouseCust.service");
		Map<String, String> params = new HashMap<>();
		String responseText = HttpClientHelper.post(url, params);
		System.out.println("responseText:" + responseText);
		JSONArray jArray= JSONArray.fromObject(responseText);
		Collection<?> collection = JSONArray.toCollection(jArray, WarehouseInfo.class);
		List<WarehouseInfo> whis = new ArrayList<WarehouseInfo>();
		Iterator<?> it = collection.iterator();
		while (it.hasNext()) {
			WarehouseInfo user = (WarehouseInfo) it.next();
			whis.add(user);
		}

		return whis;
	}

	@Override
	public List<ContainerInventory> importFreightInfo(String fileUuid) {
		FileParseService fileParseService = ComponentFactory.loadClass(FileParseService.class);
		List<List<String>> datas = fileParseService.parseExcel(fileUuid, FREIGHT_TITLE);
		List<ContainerInventory> cList = new ArrayList<>();
		for (List<String> l : datas) {
			try {
				ContainerInventory ci = new ContainerInventory();
				ci.setShipsName(l.get(0));
				ci.setWaybillNumber(l.get(1));
				ci.setCaseNumber(l.get(2));
				ci.setCaseSize(l.get(3));
				ci.setDoorsAdress(l.get(4));
				ci.setSettlementPrice(new BigDecimal(l.get(5)));
				ci.setSettlementObject(l.get(6));
				ci.setRemark(l.get(7));
				ci.setConfrimDate(DateUtils.fromDateInt(Integer.parseInt(l.get(8))));
				ci.setSettlementDate(DateUtils.fromDateInt(Integer.parseInt(l.get(9))));
				cList.add(ci);
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
		}
		return cList;
	}

	public ResultData searchInboundInfoForFinance(String inboundNo) {
		String url = ConfigPropertites.getProperties("finance.searchInboundInfoForFinance.service");
		Map<String, String> params = new HashMap<>();
		params.put("inboundNo", inboundNo);
		String responseText = HttpClientHelper.post(url, params);
		logger.info("url:" + url);
		logger.info("params:" + params);
		logger.info("responseText:" + responseText);

		ResultData result = (ResultData)JSON.toBean(responseText, ResultData.class);

		if ("error".equals(result.getStatus())) {
			throw new BusinessException(result.getMsg());
		}

		//		if ((result != null) && (result.getResult() != null) && (result.getResult().getGoodsId() != null)) {
		//			BulkstockInfoEntity bie = this.bulkstockInfoService.inquireBulkstockInfo(Long.valueOf(result.getResult().getGoodsId()));
		//			result.getResult().setUnit("吨");
		//		}

		result.getResult().setUnit("吨");
		return result;
	}

	@Override
	public WareResultDetailData searchInboundInfoForFinanceDetail(String inboundNo) {

		String url = ConfigPropertites.getProperties("finance.returnInboundDetailForFinance.service");
		String fileHead = ConfigPropertites.getProperties("finance.fileUrl.service");
		Map<String, String> params = new HashMap<>();
		params.put("inboundNo", inboundNo);
		String responseText = HttpClientHelper.post(url, params);
		logger.info("url:" + url);
		logger.info("params:" + params);
		logger.info("responseText:" + responseText);

		WareResultDetailData result = JSON.toBean(responseText, WareResultDetailData.class);

		if ("error".equals(result.getStatus())) {
			throw new BusinessException(result.getMsg());
		}

		StringBuffer photos = new StringBuffer();
		StringBuffer poundfiles = new StringBuffer();
		StringBuffer inspectionsheet_photos = new StringBuffer();
		StringBuffer cargo_photos = new StringBuffer();
		for (String s : result.getResult().getPhotofile().split(",")) {
			if (StringUtil.isBlank(s)) {
				continue;
			}
			photos.append(fileHead + s + ",");
		}
		for (String s : result.getResult().getPoundfile().split(",")) {
			if (StringUtil.isBlank(s)) {
				continue;
			}
			poundfiles.append(fileHead + s + ",");
		}
		for (String s : result.getResult().getCargo_photos().split(",")) {
			if (StringUtil.isBlank(s)) {
				continue;
			}
			cargo_photos.append(fileHead + s + ",");
		}
		for (String s : result.getResult().getInspectionsheet_photos().split(",")) {
			if (StringUtil.isBlank(s)) {
				continue;
			}
			inspectionsheet_photos.append(fileHead + s + ",");
		}
		if (photos.length() > 0) {
			photos.deleteCharAt(photos.length() - 1);
			result.getResult().setPhotofile(photos.toString());
		}
		if (poundfiles.length() > 0) {
			poundfiles.deleteCharAt(poundfiles.length() - 1);
			result.getResult().setPoundfile(poundfiles.toString());
		}
		if (cargo_photos.length() > 0) {
			cargo_photos.deleteCharAt(cargo_photos.length() - 1);
			result.getResult().setCargo_photos(cargo_photos.toString());
		}
		if (inspectionsheet_photos.length() > 0) {
			inspectionsheet_photos.deleteCharAt(inspectionsheet_photos.length() - 1);
			result.getResult().setInspectionsheet_photos(inspectionsheet_photos.toString());
		}

		return result;
	}
	
	@Override
	public WareResultDetailData2 returnOutboundDetailInfo(String pickupNumber, String warehouseId) {

		String url = ConfigPropertites.getProperties("finance.returnOutboundDetailInfo.service");
		String fileHead = ConfigPropertites.getProperties("finance.fileUrl.service");
		Map<String, String> params = new HashMap<>();
		params.put("pickupNumber", pickupNumber);
		params.put("warehouseId", warehouseId);
		String responseText = HttpClientHelper.post(url, params);
		logger.info("url:" + url);
		logger.info("params:" + params);
		logger.info("responseText:" + responseText);

		WareResultDetailData2 result = JSON.toBean(responseText, WareResultDetailData2.class);

		if ("error".equals(result.getStatus())) {
			throw new BusinessException(result.getMsg());
		}

		StringBuffer photos = new StringBuffer();
		StringBuffer poundfiles = new StringBuffer();
//		StringBuffer inspectionsheet_photos = new StringBuffer();
//		StringBuffer cargo_photos = new StringBuffer();
		for (String s : result.getResult().getPhotofile().split(",")) {
			if (StringUtil.isBlank(s)) {
				continue;
			}
			photos.append(fileHead + s + ",");
		}
		for (String s : result.getResult().getPoundfile().split(",")) {
			if (StringUtil.isBlank(s)) {
				continue;
			}
			poundfiles.append(fileHead + s + ",");
		}
//		for (String s : result.getResult().getCargo_photos().split(",")) {
//			if (StringUtil.isBlank(s)) {
//				continue;
//			}
//			cargo_photos.append(fileHead + s + ",");
//		}
//		for (String s : result.getResult().getInspectionsheet_photos().split(",")) {
//			if (StringUtil.isBlank(s)) {
//				continue;
//			}
//			inspectionsheet_photos.append(fileHead + s + ",");
//		}
		if (photos.length() > 0) {
			photos.deleteCharAt(photos.length() - 1);
			result.getResult().setPhotofile(photos.toString());
		}
		if (poundfiles.length() > 0) {
			poundfiles.deleteCharAt(poundfiles.length() - 1);
			result.getResult().setPoundfile(poundfiles.toString());
		}
//		if (cargo_photos.length() > 0) {
//			cargo_photos.deleteCharAt(cargo_photos.length() - 1);
//			result.getResult().setCargo_photos(cargo_photos.toString());
//		}
//		if (inspectionsheet_photos.length() > 0) {
//			inspectionsheet_photos.deleteCharAt(inspectionsheet_photos.length() - 1);
//			result.getResult().setInspectionsheet_photos(inspectionsheet_photos.toString());
//		}

		return result;
	}

	@Override
	public WarehouseMap showWarehouseMapForFinance(String warehouseId) {
		String url = ConfigPropertites.getProperties("finance.showWarehouseMapForFinance.service");
		Map<String, String> params = new HashMap<>();
		params.put("warehouseId", warehouseId);
		String responseText = HttpClientHelper.post(url, params);
		logger.info("url:" + url);
		logger.info("params:" + params);
		logger.info("responseText:" + responseText);

		WarehouseMap result = JSON.toBean(responseText, WarehouseMap.class);

		return result;
	}	

	@Override
	public void lockWarehouseAndInbound(String inboundNo) {
		String url = ConfigPropertites.getProperties("finance.lockWarehouseAndInbound.service");
		Map<String, String> params = new HashMap<>();
		params.put("inboundNo", inboundNo);
		String responseText = HttpClientHelper.post(url, params);
		logger.info("url:" + url);
		logger.info("params:" + params);
		logger.info("responseText:" + responseText);

		ResultData result = (ResultData)JSON.toBean(responseText, ResultData.class);

		if (!"success".equals(result.getStatus())) {
			throw new BusinessException(result.getMsg());
		}
	}

	@Override
	public void unlockInbound(String inboundNo) {
		String url = ConfigPropertites.getProperties("finance.unlockInbound.service");
		Map<String, String> params = new HashMap<>();
		params.put("inboundNo", inboundNo);
		String responseText = HttpClientHelper.post(url, params);
		logger.info("url:" + url);
		logger.info("params:" + params);
		logger.info("responseText:" + responseText);

		ResultData result = (ResultData)JSON.toBean(responseText, ResultData.class);

		if (!"success".equals(result.getStatus())) {
			throw new BusinessException(result.getMsg());
		}
	}


	@Override
	@Transactional
	public void completeOutbound(String inboundNo) {
		ContainerInventoryEntity inventory = containerInventoryService.inquireContainerInventory(null, inboundNo);
		String url = ConfigPropertites.getProperties("finance.completeOutbound.service");
		Map<String, String> params = new HashMap<>();
		params.put("inboundNo", inboundNo);
		params.put("finance_no", inventory.getFinanceNumber());
		String responseText = HttpClientHelper.post(url, params);
		logger.info("url:" + url);
		logger.info("params:" + params);
		logger.info("responseText:" + responseText);

		ResultData result = (ResultData)JSON.toBean(responseText, ResultData.class);

		if (!"success".equals(result.getStatus())) {
			throw new BusinessException(result.getMsg());
		} else {
			if (null != inventory) {
				inventory.setSupervisionState(SupervisionStateEnum.RELIEVE_SUPERVISE);
				containerInventoryService.updateContainerInventory(inventory);
			}
		}
	}

	@Override
	public ResultData getOutboundPlan(String pickupNumber, Integer productType, String consignor_id, String[] financeNumber, String[] location_id, Long[] goods_id, BigDecimal[] quantitys,
			BigDecimal[] weights, BigDecimal[] volumes, String[] locationNames, String[] locationAreas, String[] warehouseId) {
		String url = ConfigPropertites.getProperties("finance.getOutboundPlan.service");
		Map<String, String> params = new HashMap<>();
		params.put("pickupNumber", pickupNumber);
		params.put("consignor_id", consignor_id);
		StringBuffer outboundInfo = new StringBuffer("[");
		for (int i = 0; i < financeNumber.length; i++) {
			FinanceApplicationDetail finance = financeApplicationActionApi.inquireFinanceApplicationDetailByFinanceNUmber(financeNumber[i]);
			if (finance == null) {
				continue;
			}
			Integer document_type = null;
			if (finance.getProductType() == 5) {
				document_type = 18;
			} else if (finance.getProductType() == 6) {
				document_type = 19;
			}
			outboundInfo.append("{");
			outboundInfo.append("\"finance_no\":\"").append(financeNumber[i]).append("\",");
//			outboundInfo.append("\"location_id\":\"").append(location_id[i]).append("\",");
			outboundInfo.append("\"document_type\":\"").append(document_type.toString()).append("\",");
			outboundInfo.append("\"goods_id\":\"").append(goods_id[i]).append("\",");
			outboundInfo.append("\"quantity\":\"").append(quantitys[i]).append("\",");
			outboundInfo.append("\"weight\":\"").append(weights[i]).append("\",");
			outboundInfo.append("\"volume\":\"").append(volumes[i]).append("\",");
//			outboundInfo.append("\"location_name\":\"").append(locationNames[i]).append("\",");
			outboundInfo.append("\"warehouseId\":\"").append(warehouseId[i]);
//			outboundInfo.append("\"location_area\":\"").append(locationAreas[i]);
			outboundInfo.append("\"},");
		}
		if (null != outboundInfo && outboundInfo.length() > 0) {
			outboundInfo.deleteCharAt(outboundInfo.length() - 1);
		}
		outboundInfo.append("]");
		params.put("outboundInfo", outboundInfo.toString());
		System.out.println(outboundInfo);

		String responseText = HttpClientHelper.post(url, params);
		logger.info("url:" + url);
		logger.info("params:" + params);
		logger.info("responseText:" + responseText);

		ResultData result = JSON.toBean(responseText, ResultData.class);

		return result;
	}

	@Transactional
	@Override
	public String proxyCreateFinanceApplication(FinanceApplication params) {
		if (params.getEnterpriseInsurance() == null) {
			params.setEnterpriseInsurance(Boolean.FALSE);
		}

		//运费保理没有投保
		if (params.getProductType() != 4 && params.getEnterpriseInsurance() && (StringUtils.isBlank(params.getEnterpriseInsurer()) || StringUtils.isBlank(params.getEnterpriseInsuranceType()) || params.getEnterpriseInsuranceAmount() == null || params.getEnterpriseForceAmount() == null)) {
			throw new BusinessException("投保情况下,保单相关信息都不允许为空");
		}

		EnterpriseEntity enterprise = null;
		EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);

		enterprise = enterpriseService.inquireEnterprise(params.getEnterpriseId());

		EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(enterprise.getEnterpriseId());
		
		if (DateUtil.todayInt() > grade.getEffectiveEndDate()) {
			throw new BusinessException("授信已过期");
		}

		//判断是否有权限做该货品融资
		if(params.getBulkstockInfoIds()!=null && params.getBulkstockInfoIds().length>0){
			for(int i=0; i<params.getBulkstockInfoIds().length; i++) {
				BulkstockInfoEntity bie = bulkstockInfoService.inquireBulkstockInfo(params.getBulkstockInfoIds()[i]);
				FinanceBulkstockPledgeRateEntity fbpre = financeBulkstockPledgeRateService.inquireFinanceBulkstockPledgeRate(grade.getGradeEvaluationId(), bie.getBulkstockInfoId(), ProductTypeEnum.valueOf(params.getProductType()));
				if (fbpre == null) {
					throw new BusinessException("该用户不能做该货品融资或产品已过期!");
				}
			}
		}

		if (enterprise == null || (AuditStateEnum.PASS != enterprise.getAuditState() && AuditStateEnum.FINISH != enterprise.getAuditState())) {
			throw new BusinessException("企业还未通过平台审核,请等待审核通过后操作");
		}

		if (enterprise.getFreeze() != null && enterprise.getFreeze()) {
			throw new BusinessException("该企业已被冻结，不能发起融资申请！");
		}

		TemporaryCreditLineEntity temporary = temporaryCreditLineService.inquireTemporaryCreditLine(enterprise.getEnterpriseId());
		if (temporary == null) {
			temporary = new TemporaryCreditLineEntity();
			temporary.setTemporaryCreditline(BigDecimal.ZERO);
			temporary.setTemporaryCreditlineAlready(BigDecimal.ZERO);
		}

		BigDecimal remaining = grade.getCreditLine().subtract(grade.getCreditAlready()).add(temporary.getTemporaryCreditline().subtract(temporary.getTemporaryCreditlineAlready()));
		if (params.getApplicationAmount().compareTo(remaining) > 0) {
			throw new BusinessException("该企业授信额度不足！");
		}

		FinanceApplicationEntity financeEntity = FinanceApplicationCastor.proxyFromFinanceApplication(params);
		financeEntity.setProductType(ProductTypeEnum.valueOf(params.getProductType()));
		financeEntity.setApplicationCreateDatetime(DateUtil.now());
		financeEntity.setFinanceState(FinanceStateEnum.APPROVE);
		financeEntity.setProxyAccountId(FinanceSessionContext.getAccountId());
		financeEntity.setProxyAccountName(FinanceSessionContext.getAccountFullName());

		Long financeId = financeApplicationService.createFinanceApplication(financeEntity);

		List<FinanceContainerBillEntity> financeContainerBills = FinanceApplicationCastor.fromFinanceApplicationContainerBill(params);
		// 订舱信息
		if (financeEntity.getBookingSpace()) {
			Integer caseQuantities = 0;
			if (params.getQuantity() != null) {
				for (Integer q : params.getQuantity()) {
					caseQuantities += q;
				}
			}
			FinanceContainerEntity financeContainer = financeEntity.getFinanceContainer();
			financeContainer.setFinanceId(financeId);
			financeContainer.setFinanceNumber(financeEntity.getFinanceNumber());
			financeContainer.setCaseQuantity(caseQuantities);
			financeContainer.setBookingSpaceNumber(params.getBookingSpaceNumber());
			financeContainerService.createFinanceContainer(financeContainer);
		}
		for (FinanceContainerBillEntity fcbe : financeContainerBills) {
			fcbe.setFinanceId(financeId);
			fcbe.setContainerSource(ContainerSourceEnum.ENTERPRISE);
			financeContainerBillService.createFinanceContainerBill(fcbe);
		}

		List<FinanceBulkstockEntity> financeBulkstockEntities = BulkstockCastor.fromFinanceApplication(params, financeId);
		for (FinanceBulkstockEntity entity : financeBulkstockEntities) {
			BulkstockInfoEntity be = bulkstockInfoService.inquireBulkstockInfo(entity.getBulkstockInfoId());
			if (be.getMeasurement() == MeasurementEnum.VOLUME) {
				if (entity.getVolume() == null) {
					throw new BusinessException("体积不能为空");
				}
			}

			financeBulkstockService.createFinanceBulkstockEntity(entity);
			FinanceBulkstockColdStorageEntity bulkstockColdStorage = entity.getBulkstockColdStorage();
			FinanceBulkstockDangerousEntity bulkstockDangerous = entity.getBulkstockDangerous();
			if (bulkstockColdStorage != null) {
				bulkstockColdStorage.setBulkstockId(entity.getBulkstockId());
				financeBulkstockColdStorageService.createFinanceBulkstockColdStorage(bulkstockColdStorage);
			}
			if (bulkstockDangerous != null) {
				bulkstockDangerous.setBulkstockId(entity.getBulkstockId());
				financeBulkstockDangerousService.createFinanceBulkstockDangerous(bulkstockDangerous);
			}
		}

		//保存运单号
		if (StringUtil.isNotBlank(params.getWaybillNumber())) {
			FinanceContainerWaybillEntity entity = new FinanceContainerWaybillEntity();
			entity.setFinanceId(financeId);
			entity.setFinanceNumber(financeEntity.getFinanceNumber());
			entity.setEnterpriseId(financeEntity.getEnterpriseId());
			entity.setEnterpriseName(financeEntity.getEnterpriseName());
			entity.setWaybillNumber(params.getWaybillNumber());
			financeContainerWaybillService.createFinanceContainerWaybill(entity);
		}

		// 项目动态
		FinanceProcessEntity financeProcessEntity = FinanceProcessCastor.fromFinanceSubmitProcess(financeId, financeEntity.getFinanceNumber());
		financeProcessService.createFinanceProcess(financeProcessEntity);

		//消息通知
		if (FinanceStateEnum.APPROVE == financeEntity.getFinanceState()) {
			SendLetterMessage.sendLetterMessage("businessAuditState", "有新的融资审批意见未填写，请及时查看!");
		}

		if (params.getProductType() == 4) {
			LogisticsCompanyEntity lce = logisticsCompanyService.inquireLogisticsCompanyByCompanyName(params.getDeliver());
			if (lce == null) {
				throw new BusinessException("请输入系统中存在的名称!");
			}

			//运费信息
			if (params.getCaseNumbers() != null) {
				for (int i = 0; i < params.getCaseNumbers().length; i++) {
					ContainerInventoryEntity cie = new ContainerInventoryEntity();
					cie.setFinanceId(financeId);
					cie.setFinanceNumber(financeEntity.getFinanceNumber());
					cie.setEnterpriseId(financeEntity.getEnterpriseId());
					cie.setEnterpriseName(financeEntity.getEnterpriseName());
					cie.setContainerSource(BulkstockSourceEnum.FINANCE);
					cie.setWaybillNumber(params.getWaybillNumbers()[i]);
					cie.setCaseNumber(params.getCaseNumbers()[i]);
					cie.setCaseSize(params.getCaseSizes()[i]);
					cie.setAbnormal(Boolean.TRUE);
					cie.setShipsName(params.getShipNames()[i]);
					cie.setSettlementDate(params.getSettlementDates()[i]);
					cie.setEnabled(Boolean.TRUE);
					cie.setType(2);
					cie.setDoorsAdress(params.getDoorsAdresses()[i]);
					cie.setSettlementObject(params.getSettlementObjects()[i]);
					cie.setSettlementPrice(params.getSettlementPrices()[i]);
					cie.setRemark(params.getRemarks()[i]);
					cie.setConfrimDate(params.getConfirmDates()[i]);
					containerInventoryService.createContainerInventory(cie);
				}
			}

			//发票信息
			for (int i = 0; i < params.getFreightNum().length; i++) {
				FreightInfoEntity fie = new FreightInfoEntity();
				fie.setFinanceId(financeId);
				fie.setDueDate(params.getDueDate()[i]);
				fie.setFactoringAmount(params.getFactoringAmount()[i]);
				fie.setInvoiceAmount(params.getInvoiceAmount()[i]);
				fie.setInvoiceDate(params.getInvoiceDate()[i]);
				fie.setInvoiceNumber(params.getInvoiceNumber()[i]);
				fie.setOthersRemark(params.getOthersRemark()[i]);
				fie.setPurchaser(params.getPurchaser()[i]);
				fie.setReceivableAmount(params.getReceivableAmount()[i]);
				fie.setFileUuid(params.getFileUuid()[i]);
				freightInfoService.createFreightInfo(fie);

				ContainerInventoryEntity cie = new ContainerInventoryEntity();
				BeanUtils.copyProperties(fie, cie);
				cie.setFinanceId(financeId);
				cie.setFinanceNumber(financeEntity.getFinanceNumber());
				cie.setEnterpriseId(financeEntity.getEnterpriseId());
				cie.setEnterpriseName(financeEntity.getEnterpriseName());
				cie.setContainerSource(BulkstockSourceEnum.FINANCE);
				cie.setAbnormal(Boolean.TRUE);
				cie.setEnabled(Boolean.TRUE);
				cie.setType(3);
				cie.setSettlementPrice(fie.getInvoiceAmount());
				containerInventoryService.createContainerInventory(cie);
			}
		} else if (params.getProductType() == 1) {
			SupplierEntity supplier = supplierService.inquireSupplierDetail(params.getReceive());
			if (null == supplier) {
				throw new BusinessException("该供应商不存在，请先添加");
			}
		}
		
		//消息推送-业务审核businessAudit_1
		SendLetterMessage.sendLetterMessage("businessAudit_1", String.format(tmp, financeEntity.getEnterpriseName(), financeEntity.getFinanceNumber(), "商务审核"));

		return financeId.toString();
	}

	@Transactional
	@Override
	public String gmCreateFinanceApplication(
			FinanceApplication params) {
		if (params.getEnterpriseInsurance() == null) {
			params.setEnterpriseInsurance(Boolean.FALSE);
		}

		EnterpriseEntity enterprise = null;
		EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);

		List<EnterpriseEntity> enterpriseList = enterpriseService.inquireEnterpriseByEnterpriseName(params.getEnterpriseName());
		if(enterpriseList == null || enterpriseList.size() != 1) {
			throw new BusinessException("企业信息获取错误");
		}
		enterprise = enterpriseList.get(0);
		params.setEnterpriseId(enterprise.getEnterpriseId());

		EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(enterprise.getEnterpriseId());

		//判断是否有权限做该货品融资
		if(params.getBulkstockInfoIds()!=null && params.getBulkstockInfoIds().length>0){
			for(int i=0; i<params.getBulkstockInfoIds().length; i++) {
				BulkstockInfoEntity bie = bulkstockInfoService.inquireBulkstockInfo(params.getBulkstockInfoIds()[i]);
				FinanceBulkstockPledgeRateEntity fbpre = financeBulkstockPledgeRateService.inquireFinanceBulkstockPledgeRate(grade.getGradeEvaluationId(), bie.getBulkstockInfoId(), ProductTypeEnum.valueOf(params.getProductType()));
				if (fbpre == null) {
					throw new BusinessException("该用户不能做该货品融资!");
				}
			}
		}

		if (enterprise == null || (AuditStateEnum.PASS != enterprise.getAuditState() && AuditStateEnum.FINISH != enterprise.getAuditState())) {
			throw new BusinessException("企业还未通过平台审核,请等待审核通过后操作");
		}

		if (enterprise.getFreeze() != null && enterprise.getFreeze()) {
			throw new BusinessException("该企业已被冻结，不能发起融资申请！");
		}

		TemporaryCreditLineEntity temporary = temporaryCreditLineService.inquireTemporaryCreditLine(enterprise.getEnterpriseId());
		if (temporary == null) {
			temporary = new TemporaryCreditLineEntity();
			temporary.setTemporaryCreditline(BigDecimal.ZERO);
			temporary.setTemporaryCreditlineAlready(BigDecimal.ZERO);
		}

		BigDecimal remaining = grade.getCreditLine().subtract(grade.getCreditAlready()).add(temporary.getTemporaryCreditline().subtract(temporary.getTemporaryCreditlineAlready()));
		if (params.getApplicationAmount().compareTo(remaining) > 0) {
			throw new BusinessException("该企业授信额度不足！");
		}

		FinanceApplicationEntity financeEntity = FinanceApplicationCastor.proxyFromFinanceApplication(params);
		financeEntity.setProductType(ProductTypeEnum.valueOf(params.getProductType()));
		financeEntity.setApplicationCreateDatetime(DateUtil.now());
		financeEntity.setFinanceState(FinanceStateEnum.APPROVE);
		/*financeEntity.setProxyAccountId(FinanceSessionContext.getAccountId());
		financeEntity.setProxyAccountName(FinanceSessionContext.getAccountFullName());*/

		Long financeId = financeApplicationService.createFinanceApplication(financeEntity);

		List<FinanceContainerBillEntity> financeContainerBills = FinanceApplicationCastor.fromFinanceApplicationContainerBill(params);

		for (FinanceContainerBillEntity fcbe : financeContainerBills) {
			fcbe.setFinanceId(financeId);
			fcbe.setContainerSource(ContainerSourceEnum.ENTERPRISE);
			financeContainerBillService.createFinanceContainerBill(fcbe);
		}

		List<FinanceBulkstockEntity> financeBulkstockEntities = BulkstockCastor.fromFinanceApplication(params, financeId);
		for (FinanceBulkstockEntity entity : financeBulkstockEntities) {
			BulkstockInfoEntity be = bulkstockInfoService.inquireBulkstockInfo(entity.getBulkstockInfoId());
			if (be.getMeasurement() == MeasurementEnum.VOLUME) {
				if (entity.getVolume() == null) {
					throw new BusinessException("体积不能为空");
				}
			}

			financeBulkstockService.createFinanceBulkstockEntity(entity);
			FinanceBulkstockColdStorageEntity bulkstockColdStorage = entity.getBulkstockColdStorage();
			FinanceBulkstockDangerousEntity bulkstockDangerous = entity.getBulkstockDangerous();
			if (bulkstockColdStorage != null) {
				bulkstockColdStorage.setBulkstockId(entity.getBulkstockId());
				financeBulkstockColdStorageService.createFinanceBulkstockColdStorage(bulkstockColdStorage);
			}
			if (bulkstockDangerous != null) {
				bulkstockDangerous.setBulkstockId(entity.getBulkstockId());
				financeBulkstockDangerousService.createFinanceBulkstockDangerous(bulkstockDangerous);
			}
		}

		// 项目动态
		FinanceProcessEntity financeProcessEntity = FinanceProcessCastor.fromFinanceSubmitProcess(financeId, financeEntity.getFinanceNumber());
		financeProcessService.createFinanceProcess(financeProcessEntity);

		//消息通知
		if (FinanceStateEnum.APPROVE == financeEntity.getFinanceState()) {
			SendLetterMessage.sendLetterMessage("businessAuditState", "有新的融资审批意见未填写，请及时查看!");
		}

		return financeId.toString();
	}
}
